• Currently, the most commonly-used
language for embedded systems
• “High-level assembly”
• Very portable: compilers exist for virtually
every processor
• Easy-to-understand compilation
• Produces efficient code
• Fairly concise
• Developed between 1969 and 1973 along
with Unix
• Due mostly to Dennis Ritchie
• Designed for systems programming
– Operating systems
– Utility programs
– Compilers
– Filters
• Evolved from B, which evolved from BCPL
#include<stdio.h>
int main()
{
--other statements
}
• The files that are specified in the include
section is called as header file
• These are precompiled files that has some
functions defined in them
• We can call those functions in our program
by supplying parameters
• Header file is given an extension .h
• C Source file is given an extension .c
• This is the entry point of a program
• When a file is executed, the start point is the
main function
• From main function the flow goes as per the
programmers choice.
• There may or may not be other functions
written by user in a program
• Main function is compulsory for any c
program
#include<stdio.h>
int main()
{
printf(“Hello”);
return 0;
}
• This program prints Hello on the screen
when we execute it
• Type a program
• Save it
• Compile the program – This will generate an
exe file (executable)
• Run the program (Actually the exe created out
of compilation will run and not the .c file)
• In different compiler we have different option
for compiling and running. We give only the
concepts.
• Single line comment
– // (double slash)
– Termination of comment is by pressing enter
key
• Multi line comment
/*….
…….*/
This can span over to multiple lines
• arithmetic: + – * / %
• comparison: == != < <= > >=
• bitwise logical: & | ^ ~
• shifting: << >>
• lazy logical: && || !
• conditional: ? :
• assignment: = += -=
• increment/decrement: ++ --
• sequencing: ,
• pointer: * -> & []
• and: &
• or: |
• xor: ^
• not: ~
• left shift: <<
• right shift: >>
• Useful for bit-field manipulations
#define MASK 0x040
if (a & MASK) { … } /* Check bits */
c |= MASK; /* Set bits */
c &= ~MASK; /* Clear bits */
d = (a & MASK) >> 4; /* Select field */
• Syntax:
condition ? result1 : result2
If the condition is true, result1 is returned
else result2 is returned.
• 10==5 ? 11: 12
10!=5 ? 4 : 3
12>8 ? a : b
• A data type defines a collection of data
objects and a set of predefined operations
on those objects.
• Variables are data that will keep on changing
• Declaration
<<Data type>> <<variable name>>;
int a;
• Definition
<<varname>>=<<value>>;
a=10;
• Usage
<<varname>>
a=a+1; //increments the value of a by 1
• Should not be a reserved word like int etc..
• Should start with a letter or an
underscore(_)
• Can contain letters, numbers or underscore.
• No other special characters are allowed
including space
• Variable names are case sensitive
– A and a are different.
• char ch;
• int i;
• i = ‘a’; /* i is now 97 */
• ch = 65; /* ch is now ‘A’ */
• ch = ch + 1; /* ch is now ‘B’ */
• ch++; /* ch is now ‘C’ */
• if(‘a’ <= ch && ch <= ‘z’)
• for(ch = ‘A’; ch <= ‘Z’; ch++)
• The syntax of for loop is
for(initialisation;condition checking;increment)
{
set of statements
}
Eg: Program to print Hello 10 times
for(I=0;I<10;I++)
{
printf(“Hello”);
}
• The syntax of do while loop
do
{
set of statements
}while(condn);
Eg:
i=10; Output:
do 10987654321
{
printf(“%d”,i);
i--;
}while(i!=0)
if (condition)
{
stmt 1; //Executes if Condition is true
}
else
{
stmt 2; //Executes if condition is false
}
switch(var)
{
case 1: //if var=1 this case executes
stmt;
break;
case 2: //if var=2 this case executes
stmt;
break;
default: //if var is something else this will execute
stmt;
}
• When the break statement is executed
inside a loop-statement, the loop-statement
is terminated immediately
• The execution of the program will continue
with the statement following the loop-
statement
• Syntax :
break;
•When the continue statement is executed
inside a loop-statement, the program will
skip over the remainder of the loop-body
to the end of the loop.
•Syntax
Continue;
• Array
– Group of consecutive memory locations
– Same name and type
• To refer to an element, specify
– Array name
– Position number
• Format:
arrayname[ position number ]
– First element at position 0
– n element array named c:
• c[ 0 ], c[ 1 ]...c[ n – 1 ]
• When declaring arrays, specify
– Name
– Type of array
– Number of elements
arrayType arrayName[ numberOfElements ];
– Examples:
int c[ 10 ];
float myArray[ 3284 ];
• Declaring multiple arrays of same type
– Format similar to regular variables
– Example:
int b[ 100 ], x[ 27 ];
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements
become 0
int n[ 5 ] = { 0 }
• All elements 0
– If too many a syntax error is produced syntax error
– C arrays have no bounds checking
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore 5 element array
• Initialization
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
– Initializers grouped by row in braces
– If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
• Referencing elements
– Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
1 2
3 4
1 0
3 4
So far we have used one-dimensional (1D) arrays,
but we can also use arrays with 2 or more
dimensions. 2D arrays essentially correspond to
matrices.
Example:
• int A; // single variable
• int B[6]; // 1D array
• int C[3][4]; // 2D array (matrix)
• int D[3][4][5]; // 3D array
• int E[3][4][5][3]; // 4D array
• //etc
• A string is a sequence of characters treated
as a group
• array can be of any length
• end of string is indicated by a delimiter, the
zero character ‘0’
"A String" A 0gnirtS
• String literal values are represented by sequences
of characters between double quotes (“)
• Examples
– “” - empty string
– “hello”
• “a” versus ‘a’
– ‘a’ is a single character value (stored in 1 byte) as the
ASCII value for a
– “a” is an array with two characters, the first is a, the
second is the character value 0
• Allocate an array of a size large enough to hold the
string (plus 1 extra value for the delimiter)
• Examples (with initialization):
char str1[6] = “Hello”;
char str2[] = “Hello”;
char *str3 = “Hello”;
char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’0’};
• C provides a wide range of string functions for
performing different string tasks
• Examples
– strlen(str) – To find length of string str
– strrev(str) – Reverses the string str as rts
– strcat(str1,str2) – Appends str2 to str1 and returns str1
– strcpy(st1,st2) – copies the content of st2 to st1
– strcmp(s1,s2) – Compares the two string s1 and s2
– strcmpi(s1,s2) – Case insensitive comparison of strings
• Functions come from the utility library string.h
– #include <string.h> to use
• A pointer is a variable whose value is the
address of another variable, i.e., direct
address of the memory location. Like any
variable or constant, you must declare a
pointer before you can use it to store any
variable address. The general form of a
pointer variable declaration is:
• type *var-name;
• There are few important operations, which we
will do with the help of pointers very
frequently.
• we define a pointer variable
• assign the address of a variable to a pointer
• finally access the value at the address
available in the pointer variable. This is done
by using unary operator * that returns the
value of the variable located at the address
specified by its operand. Following example
makes use of these operations:
• Functions
– Modularize a program
– All variables declared inside functions are local variables
• Known only in function defined
– Parameters
• Communicate information between functions
• Local variables
• Benefits of functions
– Divide and conquer
• Manageable program development
– Software reusability
• Use existing functions as building blocks for new programs
• Abstraction - hide internal details (library functions)
– Avoid code repetition
• Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Function-name: any valid identifier
– Return-value-type: data type of the result (default
int)
• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares
parameters
• A type must be listed explicitly for each parameter unless,
the parameter is of type int
• Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Declarations and statements: function body (block)
• Variables can be declared inside blocks (can be nested)
• Functions can not be defined inside other functions
– Returning control
• If nothing returned
– return;
– or, until reaches right brace
• If something returned
– return expression;
• Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify
argument
• Avoids accidental changes
• Call by reference
– Passes original argument
– Changes in function effect original
– Only used with trusted functions
• Recursive functions
– Functions that call themselves
– Can only solve a base case
– Divide a problem up into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion step) to
solve what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole
problem
• Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
• 5! = 5 * 4!
• 4! = 4 * 3! ...
– Can compute factorials recursively
– Solve base case (1! = 0! = 1) then plug in
• 2! = 2 * 1! = 2 * 1 = 2;
• 3! = 3 * 2! = 3 * 2 = 6;
• A structure is a collection of variables under
a single name. These variables can be of
different types, and each has a name which
is used to select it from the structure. A
structure is a convenient way of grouping
several pieces of related information
together.
• Structures are user defined data types
• It is a collection of heterogeneous data
• It can have integer, float, double or character
data in it
• We can also have array of structures
struct <<structname>>
{
members;
}element;
We can access element.members;
•Compound data:
•A date is
– an int month and
– an int day and
– an int year
• The typedef operator is used for creating
alias of a data type
• For example I have this statement
typedef int integer;
Now I can use integer in place of int
i.e instead of declaring int a;, I can use
integer a;
This is applied for structures too.
• typedef struct student
• {
• int id;
• Char name[10];
• }s;
• Now I can put
• s s1,s2;
• A union value doesn’t “know” which case it
contains
•Choices:
•An element is
– an int i or
– a char c
union AnElt {
int i;
char c;
} elt1, elt2;
elt1.i = 4;
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
if (elt1 currently has a char) …
Symbolic constants
#define PI 3.1415926535
Macros with arguments for emulating inlining
#define min(x,y) ((x) < (y) ? (x) :
(y))
Conditional compilation
#ifdef __STDC__
File inclusion for sharing of declarations
#include “myheaders.h”
Header file dependencies usually form a directed acyclic
graph (DAG)
How do you avoid defining things twice?
Convention: surround each header (.h) file with a
conditional:
#ifndef __MYHEADER_H__
#define __MYHEADER_H__
/* Declarations */
#endif
C language

C language

  • 2.
    • Currently, themost commonly-used language for embedded systems • “High-level assembly” • Very portable: compilers exist for virtually every processor • Easy-to-understand compilation • Produces efficient code • Fairly concise
  • 4.
    • Developed between1969 and 1973 along with Unix • Due mostly to Dennis Ritchie • Designed for systems programming – Operating systems – Utility programs – Compilers – Filters • Evolved from B, which evolved from BCPL
  • 5.
  • 6.
    • The filesthat are specified in the include section is called as header file • These are precompiled files that has some functions defined in them • We can call those functions in our program by supplying parameters • Header file is given an extension .h • C Source file is given an extension .c
  • 7.
    • This isthe entry point of a program • When a file is executed, the start point is the main function • From main function the flow goes as per the programmers choice. • There may or may not be other functions written by user in a program • Main function is compulsory for any c program
  • 8.
    #include<stdio.h> int main() { printf(“Hello”); return 0; } •This program prints Hello on the screen when we execute it
  • 9.
    • Type aprogram • Save it • Compile the program – This will generate an exe file (executable) • Run the program (Actually the exe created out of compilation will run and not the .c file) • In different compiler we have different option for compiling and running. We give only the concepts.
  • 10.
    • Single linecomment – // (double slash) – Termination of comment is by pressing enter key • Multi line comment /*…. …….*/ This can span over to multiple lines
  • 12.
    • arithmetic: +– * / % • comparison: == != < <= > >= • bitwise logical: & | ^ ~ • shifting: << >> • lazy logical: && || ! • conditional: ? : • assignment: = += -= • increment/decrement: ++ -- • sequencing: , • pointer: * -> & []
  • 13.
    • and: & •or: | • xor: ^ • not: ~ • left shift: << • right shift: >> • Useful for bit-field manipulations #define MASK 0x040 if (a & MASK) { … } /* Check bits */ c |= MASK; /* Set bits */ c &= ~MASK; /* Clear bits */ d = (a & MASK) >> 4; /* Select field */
  • 14.
    • Syntax: condition ?result1 : result2 If the condition is true, result1 is returned else result2 is returned. • 10==5 ? 11: 12 10!=5 ? 4 : 3 12>8 ? a : b
  • 16.
    • A datatype defines a collection of data objects and a set of predefined operations on those objects.
  • 18.
    • Variables aredata that will keep on changing • Declaration <<Data type>> <<variable name>>; int a; • Definition <<varname>>=<<value>>; a=10; • Usage <<varname>> a=a+1; //increments the value of a by 1
  • 19.
    • Should notbe a reserved word like int etc.. • Should start with a letter or an underscore(_) • Can contain letters, numbers or underscore. • No other special characters are allowed including space • Variable names are case sensitive – A and a are different.
  • 20.
    • char ch; •int i; • i = ‘a’; /* i is now 97 */ • ch = 65; /* ch is now ‘A’ */ • ch = ch + 1; /* ch is now ‘B’ */ • ch++; /* ch is now ‘C’ */ • if(‘a’ <= ch && ch <= ‘z’) • for(ch = ‘A’; ch <= ‘Z’; ch++)
  • 22.
    • The syntaxof for loop is for(initialisation;condition checking;increment) { set of statements } Eg: Program to print Hello 10 times for(I=0;I<10;I++) { printf(“Hello”); }
  • 23.
    • The syntaxof do while loop do { set of statements }while(condn); Eg: i=10; Output: do 10987654321 { printf(“%d”,i); i--; }while(i!=0)
  • 24.
    if (condition) { stmt 1;//Executes if Condition is true } else { stmt 2; //Executes if condition is false }
  • 25.
    switch(var) { case 1: //ifvar=1 this case executes stmt; break; case 2: //if var=2 this case executes stmt; break; default: //if var is something else this will execute stmt; }
  • 26.
    • When thebreak statement is executed inside a loop-statement, the loop-statement is terminated immediately • The execution of the program will continue with the statement following the loop- statement • Syntax : break;
  • 28.
    •When the continuestatement is executed inside a loop-statement, the program will skip over the remainder of the loop-body to the end of the loop. •Syntax Continue;
  • 31.
    • Array – Groupof consecutive memory locations – Same name and type • To refer to an element, specify – Array name – Position number • Format: arrayname[ position number ] – First element at position 0 – n element array named c: • c[ 0 ], c[ 1 ]...c[ n – 1 ]
  • 33.
    • When declaringarrays, specify – Name – Type of array – Number of elements arrayType arrayName[ numberOfElements ]; – Examples: int c[ 10 ]; float myArray[ 3284 ]; • Declaring multiple arrays of same type – Format similar to regular variables – Example: int b[ 100 ], x[ 27 ];
  • 34.
    • Initializers int n[5 ] = { 1, 2, 3, 4, 5 }; – If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 0 } • All elements 0 – If too many a syntax error is produced syntax error – C arrays have no bounds checking • If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 }; – 5 initializers, therefore 5 element array
  • 35.
    • Initialization – intb[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; – Initializers grouped by row in braces – If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; • Referencing elements – Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); 1 2 3 4 1 0 3 4
  • 36.
    So far wehave used one-dimensional (1D) arrays, but we can also use arrays with 2 or more dimensions. 2D arrays essentially correspond to matrices. Example: • int A; // single variable • int B[6]; // 1D array • int C[3][4]; // 2D array (matrix) • int D[3][4][5]; // 3D array • int E[3][4][5][3]; // 4D array • //etc
  • 39.
    • A stringis a sequence of characters treated as a group • array can be of any length • end of string is indicated by a delimiter, the zero character ‘0’ "A String" A 0gnirtS
  • 40.
    • String literalvalues are represented by sequences of characters between double quotes (“) • Examples – “” - empty string – “hello” • “a” versus ‘a’ – ‘a’ is a single character value (stored in 1 byte) as the ASCII value for a – “a” is an array with two characters, the first is a, the second is the character value 0
  • 41.
    • Allocate anarray of a size large enough to hold the string (plus 1 extra value for the delimiter) • Examples (with initialization): char str1[6] = “Hello”; char str2[] = “Hello”; char *str3 = “Hello”; char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’0’};
  • 42.
    • C providesa wide range of string functions for performing different string tasks • Examples – strlen(str) – To find length of string str – strrev(str) – Reverses the string str as rts – strcat(str1,str2) – Appends str2 to str1 and returns str1 – strcpy(st1,st2) – copies the content of st2 to st1 – strcmp(s1,s2) – Compares the two string s1 and s2 – strcmpi(s1,s2) – Case insensitive comparison of strings • Functions come from the utility library string.h – #include <string.h> to use
  • 44.
    • A pointeris a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is: • type *var-name;
  • 45.
    • There arefew important operations, which we will do with the help of pointers very frequently. • we define a pointer variable • assign the address of a variable to a pointer • finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations:
  • 48.
    • Functions – Modularizea program – All variables declared inside functions are local variables • Known only in function defined – Parameters • Communicate information between functions • Local variables • Benefits of functions – Divide and conquer • Manageable program development – Software reusability • Use existing functions as building blocks for new programs • Abstraction - hide internal details (library functions) – Avoid code repetition
  • 49.
    • Function definitionformat return-value-type function-name( parameter-list ) { declarations and statements } – Function-name: any valid identifier – Return-value-type: data type of the result (default int) • void – indicates that the function returns nothing – Parameter-list: comma separated list, declares parameters • A type must be listed explicitly for each parameter unless, the parameter is of type int
  • 50.
    • Function definitionformat (continued) return-value-type function-name( parameter-list ) { declarations and statements } – Declarations and statements: function body (block) • Variables can be declared inside blocks (can be nested) • Functions can not be defined inside other functions – Returning control • If nothing returned – return; – or, until reaches right brace • If something returned – return expression;
  • 51.
    • Call byvalue – Copy of argument passed to function – Changes in function do not effect original – Use when function does not need to modify argument • Avoids accidental changes • Call by reference – Passes original argument – Changes in function effect original – Only used with trusted functions
  • 52.
    • Recursive functions –Functions that call themselves – Can only solve a base case – Divide a problem up into • What it can do • What it cannot do – What it cannot do resembles original problem – The function launches a new copy of itself (recursion step) to solve what it cannot do – Eventually base case gets solved • Gets plugged in, works its way up and solves whole problem
  • 53.
    • Example: factorials –5! = 5 * 4 * 3 * 2 * 1 – Notice that • 5! = 5 * 4! • 4! = 4 * 3! ... – Can compute factorials recursively – Solve base case (1! = 0! = 1) then plug in • 2! = 2 * 1! = 2 * 1 = 2; • 3! = 3 * 2! = 3 * 2 = 6;
  • 55.
    • A structureis a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together.
  • 56.
    • Structures areuser defined data types • It is a collection of heterogeneous data • It can have integer, float, double or character data in it • We can also have array of structures struct <<structname>> { members; }element; We can access element.members;
  • 57.
    •Compound data: •A dateis – an int month and – an int day and – an int year
  • 58.
    • The typedefoperator is used for creating alias of a data type • For example I have this statement typedef int integer; Now I can use integer in place of int i.e instead of declaring int a;, I can use integer a; This is applied for structures too.
  • 59.
    • typedef structstudent • { • int id; • Char name[10]; • }s; • Now I can put • s s1,s2;
  • 60.
    • A unionvalue doesn’t “know” which case it contains •Choices: •An element is – an int i or – a char c union AnElt { int i; char c; } elt1, elt2; elt1.i = 4; elt2.c = ’a’; elt2.i = 0xDEADBEEF; if (elt1 currently has a char) …
  • 62.
    Symbolic constants #define PI3.1415926535 Macros with arguments for emulating inlining #define min(x,y) ((x) < (y) ? (x) : (y)) Conditional compilation #ifdef __STDC__ File inclusion for sharing of declarations #include “myheaders.h”
  • 63.
    Header file dependenciesusually form a directed acyclic graph (DAG) How do you avoid defining things twice? Convention: surround each header (.h) file with a conditional: #ifndef __MYHEADER_H__ #define __MYHEADER_H__ /* Declarations */ #endif