INTRODUCTION TO C

Embedded

Wireless

Telecom

Table of Contents





Telecom

Introduction to C
A simple C program
Basic data types
Variables
Operators
Control flow
Arrays and pointers
Functions
Structures and Union
Files

Wireless

Embedded

www.globaledgesoft.com

Introdunction to C
C is a middle level language that was
originally developed by Dennis Ritchie .

Embedded

It combines the best elements of high
level languages with the control and
flexibility of assembly languages.

Wireless

C is a structured programming language.

www.globaledgesoft.com

Telecom

globaledgesoft. World”).h> Wireless int main() { printf(“\nHello.A simple C program Embedded #include<stdio. Telecom } www.com .

BASIC DATA TYPES short int Int long int unsigned long int -32.648(231-1) 0 4.648(231-1) 0 4.294.294.147.com Telecom unsigned int Largest Value Wireless unsigned short int Smallest Value Embedded Type (32 bit) .147.483.767(215-1) 0 65.globaledgesoft.648(-231) 2.483.483.648(-231) 2.967.967.483.147.295 -2.535(216-1) -2.295 www.147.768(-215) 32.

globaledgesoft.4E +38 3.4E+38 double -1..com .) char Smallest Value Largest Value -128 127 -3.7E+308 1.BASIC DATA TYPES(CONTD.7E+308 Wireless float Embedded Type (32 bit) Telecom www.

Embedded Variable is a named location in memory that is used to hold a value.//assignment int var = 5. //declaration var = 5.globaledgesoft.com Telecom The general form of declaring a variable is. Eg: int var.  . Datatype variable_list.Variables  www. //initialization  Wireless All variables must be declared before use.

com Wireless  Arithmetic operators Relational and Logical operators Bitwise operators Increment and Decrement operators Conditional operators Embedded  .globaledgesoft.Operators    Telecom www.

Control Flow Iteration statements while (expr) stmt.com Telecom  Wireless Selection statements if (expr) stmt.expr2. www. for (expr1.globaledgesoft.expr3) stmt. default } Embedded  ... switch (expr) {case . if (expr) stmt1 else stmt2. do stmt while expr.

syntax:datatype var_name[size]. // initialization  Embedded Array: An array is a collection of variables of the same type that are referred through a common name.com Wireless Pointers: A pointer is a variable that holds the address of another variable.  . Eg: int *ptr.globaledgesoft. //declaring a pointer variable Int *ptr = &a.Array and Pointer Telecom www.

 www.  Embedded  .com Telecom The general form of a function is return type fun_name(parameter list) { body of the function } Wireless The place where all the program activity occurs.globaledgesoft.Functions Building blocks of c .

globaledgesoft.   Telecom www.Structure and Union Wireless Union: A union is a memory location that is shared by different types of variables.com . grouped together in a single name for convenient handling. Embedded Structures: Structure is a collection of same or different data type.

For files you want to read or write. Wireless  A file is viewed as a stream of bytes. Embedded   www.com Telecom  . Eg: FILE *fp.Files Files must be opened before being accessed. you need a file pointer.globaledgesoft.

Data Types and Expressions Embedded Wireless Telecom .

Table of Contents Wireless Telecom www.com Embedded  Introduction  Data Types in C  Built-in Data Types  Derived Data Types  Expression  Assignment Operator and Expression  Conditional Expression  Storage class .globaledgesoft.

com .globaledgesoft.Introduction we used in our program and tells the compiler how many bytes of memory to be allocated for the variable Telecom Example : int a. Wireless Syntax : <Data type> <variable name> Embedded  Data Types specifies what type of data www.

com Telecom  Derived data types Wireless  Built-in data types Embedded  In C we have two kind of Data types .Data Types in C 1)Built-in data types 2)Derived data types These are data types which are predefined that cannot be modified By using built-in data type collection we can derive a new data type www.globaledgesoft.

globaledgesoft.Built-in Data Type Embedded  Built-in Data type in C contains Wireless nt : size 2 or 4 bytes Char : size 1 Byte Unsigned int :size 2 or 4 Bytes Telecom www.com .

4E-4932 to 1.535(unsigned)  Float : size 4 bytes range 1.3E-308 to 1.globaledgesoft.7E+308 precision 15 decimal places  Long Double : size 10 bytes range 3.Built-in Data Type(cont) Wireless Telecom 2 bytes range -32.com Embedded  Short : size .4E+38 precision 6 decimal places  Double : size 8 bytes range 2.1E+4932 precision 19 decimal places www.767 or 0 to 65.768 to 32.2E-38 to 3.

Derived Data types Telecom struct structname { Variables }structure object. A[] is array subscript  Structure : it is collection of heterogeneous elements of all basic data types.globaledgesoft.com . it allocates memory for all data types inside a structure  www. Wireless  Syntax Embedded Array : it is a collection of homogeneous elements of given data type  Example: int a[10].

com Telecom  Pointer : It only contains the address of another Wireless elements but it allocates memory for only a data type that has highest memory Syntax union unionname { Variables }union object. www. Embedded  Union :it is also collection of heterogeneous .Derived Data types(cont)  variable. Size is 4 bytes  Example int *p.globaledgesoft.

globaledgesoft. constant and operators written according to the syntax of C language Example : a * b – c  Expression is evaluated in assignment statement form Variable = Expression d=a*b–c  Expression will be evaluated based on precedence of operator Highest priority = * / % www.Expression Wireless Telecom variables.com Lowest priority = + - Embedded  An expression is a combination of .

evaluated  else expression 3 will be evaluated www.com Telecom  If expression 1 is true expression 2 will be Wireless  Syntax Embedded  Based on condition expression will be .Conditional Expression evaluated expr1 ? expr2 : expr3  Example z = (a > b) ? a : b.globaledgesoft.

globaledgesoft.Storage class Embedded Wireless Topics :  Automatic variables  External variables  Static variables  Register variables Telecom www.com .

 .globaledgesoft. int number.Auto Auto declare inside a function in which they are to be utilized. an automatic variable. by default.com Telecom Variables declared inside a function without storage class specification is. auto int number. Wireless   www. Embedded This variables are private(local) to the function in which they are declared. eg.

 .globaledgesoft.  Wireless It is declared using the keyword static like static int x.static  Static variables are initialized only once. when the program is compiled.  www.com Telecom It may be of external or internal type depending on the place of there declaration. Embedded The value of static variables persists until the end of the program.

eg.  Wireless C will automatically convert register variables into nonregister variables once the limit is reached.com Telecom Don’t try to declare a global variable as register. Because the register will be occupied during the lifetime of the program.  Embedded Storage variables are stored in one of the machine’s register and are declared using register keyword.globaledgesoft. register int c  .Register www.

 .com Wireless An external static variable seems similar simple external variable but their difference is that static external variable is available only within the file where it is defined while simple external variable can be accessed by other files.Extern Telecom www.globaledgesoft.  Embedded An external static variable is declared outside of all functions and is available to all the functions in the program.

Operators in C Mukesh kumar D Embedded Wireless Telecom .

com Telecom Operators in C Arithmetic operators Increment/decrement operators Relational operators Logical operators Conditional operator Bitwise operators Special operators Wireless         Embedded  Introduction .Table of Contents www.globaledgesoft.

c are operands C program provides wide variety of operators  .com Embedded Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations. here '=' and '+' are operators and a.Introduction Wireless Telecom www.globaledgesoft.b.   Eg: a=b+c.

Operators in C

Wireless
Telecom

www.globaledgesoft.com

Embedded







C Language supports following types of
operators,
Arithmetic operators
Increment/decrement operators
Relational operators
Logical operators
Conditional operator
Bitwise operators
Special operators

Arithmetic Operators
are used to perform
mathematical calculations like addition,
subtraction, multiplication, division and
modulus.
Example

+

Addition

A+B

-

Subtraction

A-B

*

Multiplication

A*B

/

Division

A/B

%
++

Modulus
Arithmetic
operators in C A%B
Increment

i++
www.globaledgesoft.com

Telecom

operations

Wireless

Operators

Embedded

 Arithmetic operators

Relational Operators
Relational operators are used to compare
the value of two
variables.
Example

>

Greater than

x>y

<

Lesser than

x<y

>=

Greater than
or equal to

x>=y

<=
==

Lesser than
x<=
or equal to
Relational operators in C
Equal to

x==y
www.globaledgesoft.com

Telecom

operation

Wireless

Operator

Embedded

Example && Logical AND x&& y || LOGICAL OR x||y ! Logical NOT !(x&&y) www. logical OR (||) and logical NOT (!). They are. logical AND (&&).globaledgesoft.com Telecom Operation Wireless Operator Embedded  .Logical Operators There are 3 logical operators in C language.

com .Conditional Operators Telecom Working of the ? Operator: Ex: m=2. n=3 r=(m>n) ? m : n.globaledgesoft.  Syntax : exp1 ? exp2 : exp3 Where exp1. Wireless  Embedded Conditional operators return one value if condition is true and returns another value is condition is false.exp2 and exp3 are expressions  www.

globaledgesoft.Bitwise operators Bitwise operator works on bits and perform bit-by-bit operation Operator Meaning | Bitwise OR ~ Bitwise NOT ^ Bitwise XOR << Left shift >> Right shift Telecom Bitwise AND Wireless & Embedded  www.com .

Wireless Telecom Right Shift  Shift n bits to right  Eg:a>>=5. www..Bitwise operators contd.globaledgesoft.com . Embedded Left Shift: • Shift n bits to left • Eg: a<<=3.

Special operators There are few other operators supported by C Language. Returns 4 if a is an integer & Returns the address of a variable &a will gives actual address of variable a * Pointer to a variable *a will be a pointer to a variable .com Telecom Description Wireless Operator Embedded  .c.globaledgesoft. Example sizeof() Returns the size of a variable sizeof(a). www.b. Used to link related expression together int a.

Precedence of operators Precedence and Associativity of C Operators Type of Operation Associativity Left to right prefix ++ and prefix –– sizeof & * + – ~ ! Unary Right to left typecasts Unary Right to left * / % Multiplicative Left to right + – Additive Left to right << >> Bitwise shift Left to right < > <= >= Relational Left to right == != Equality Left to right & Bitwise-AND Left to right ^ Bitwise-exclusive-OR Left to right | Bitwise-inclusive-OR Left to right && Logical-AND Left to right || Logical-OR Left to right ? : Conditional-expression Right to left = *= /= %= www.globaledgesoft.com Telecom Expression Wireless [ ] ( ) . –> postfix ++ and postfix –– Embedded Symbol .

Control Flow Embedded Wireless Telecom .

globaledgesoft.For & Do While  Break  Continue  Goto  Labels .Table of Contents Wireless Telecom www.com Embedded  If – else  Else – if  Switch  Loops – While.

 Expression May Be checked with Conditions.If else Telecom www. Embedded  Used To Express Decisions. else statement2.  Syntax : .com Wireless if ( Expression ) statement1.globaledgesoft.

Else s3. Else if (Expression2)s2. Telecom www.com Wireless if(Expression1) s1.globaledgesoft.  If expression satisfies condition. Embedded  Multiway  Syntax: .  Control flows in order from top. statements within that condition gets executed.Else .if decisions .

Switch Wireless according to The options and expressions.  Syntax: Switch(opt){ case opt1:{} case opt2:{} Default : {} } Embedded  Multiway decisions and branches Telecom www.globaledgesoft.com .

globaledgesoft.For Wireless Telecom for(initialization.  Loop runs till condition satisfies. .test condition.com Embedded  Syntax : .inc/dec){ Statements}  Entry check loop..inc/dec done in each iteration.  Other than Initialization condition.  Initialization for variables done and executed.  for(.' is required www.) -is an infinite loop  Any of the expressions can be omitted but '.

Do - While

Telecom

www.globaledgesoft.com

Wireless

do{
statements;}while(Condition/Expression);
 Exit check loop.
 No initialization for variables.
 Nested loops Are Possible.
 Break Stops The Execution of Loop and
Control Comes Out.

Embedded

 Syntax :

Break & Continue

Telecom

www.globaledgesoft.com

Wireless

Loop .
 Continue Statement Transfers Control To
The Beginning Of The Loop.
 In Do – While loop Continue statement
Transfers Control To - While(con/exp).
 Break And Continue Statements Used
Inside Of Loops Only.

Embedded

 Break Statement Stops The Execution Of

Goto & Labels
used with label.

Telecom

www.globaledgesoft.com

Wireless

Goto label;
 Label can be anywhere inside the same
function as goto
 Label is followed with colon.
 Goto statement is used to break the loop
of deeply nested loop structures ( Where
break cannot be used since it breaks only
innermost loop).

Embedded

 Goto statement is
 Syntax :

FUNCTION POINTERS Embedded Wireless Telecom .

?  Definition  Need of function pointers  Assign and call using function pointers  Array of function pointers.Table of Contents Embedded Wireless  Introduction  What are function pointers . Telecom www.globaledgesoft.com .

 Pointers can also point to c functions.. pointers that point to functions Embedded  Every type of variables with the exception ..that is. float. only a few enable you to define pointers to code -.  We can reference variables of the type char. etc. int.globaledgesoft.  While many programming languages support the concept of pointers to data.com Wireless of register has an address. by using pointers).Introduction Telecom www. through their address (ie .

What are function Pointers?

Telecom

www.globaledgesoft.com

Wireless

to data, it is possible to have pointers to
functions
 Functions occupy memory locations
therefore every function has an address
just like each variable
 The pointers which points to the functions
are called function pointers.

Embedded

 C does not require that pointers only point

Define a Function Pointer

(*funcPointer) is needed because there are
precedence relationships in declaration
just as there are in expressions
www.globaledgesoft.com

Telecom

 The extra parentheses around

Wireless

variable, it must be defined as usual.
Eg,
int (*funcPointer) (int, char, int);
funcPointer is a pointer to a function.

Embedded

 A function pointer is nothing else than a

Why do we need function Pointers?

Telecom

www.globaledgesoft.com

Wireless

used to perform similar tasks on data
(eg sorting)
 One common use is in passing a function
as a parameter in a function call.
 Can pass the data and the function to be
used to some control function
 Greater flexibility and better code reuse

Embedded

 Useful when alternative functions maybe

Assign an address to a Function Pointer infront of the function’s name  assign an address to the function pointer int (*funcPointer) (int. return a+b+c. } funcPointer= welcome.globaledgesoft. char. Telecom www. int). int c){ printf(“ Welcome to my presentation”). //alternative using address operator Embedded  It is optional to use the address operator & .com Wireless int welcome ( int a. //assignment funcPointer=&welcome. char b.

2 ). answer=(* funcPointer) (7. . ’A’ . int). 2 ).com Telecom // calling a function using function pointer answer= funcPointer (7.Call using function pointers There are two alternatives * Use the name of the function pointer * Can explicitly dereference it Embedded int (*funcPointer) (int. char.globaledgesoft. Wireless www. ’A’ .

Wireless  This offers the possibility to select a function using an index  Eg. We can write functions that implement these command then store pointers to the functions in an array.com Telecom suppose that we’re writing a program that displays a menu of commands for the user to choose from.Array of function pointers pointers to data therefore we can have arrays of pointers to functions www.globaledgesoft. Embedded  C treats pointers to functions just like .

.. print_cmd.globaledgesoft. close_cmd. open_cmd.exit_cmd }.Cont. Telecom file_cmd[n](). save_as_cmd.we can subscript the file_cmd array to find out which function to call Wireless  Embedded void (*file_cmd[]) (void) = { new_cmd. If the user selects a command between 0 and 6.com . www. save_cmd .then.

POINTERS AND ARRAYS Kiruthika . N Embedded Wireless Telecom .

com Telecom  Wireless  Define pointer Why pointer ? Pointer Arithmetic Pointer used as array Array of pointer Pointer to pointer Constant pointer and pointer to a constant Types of pointer Embedded  .globaledgesoft.Table of Contents      www.

Define pointer A pointer is a variable whose value is the address of another variable..e.globaledgesoft. i. direct address of the memory location. Telecom www. Embedded  Wireless Int a = 3.com . Int *ptr = &a.

/* A untyped pointer */ return 0.h> int main() { int *ptr_A.com Wireless #include<stdio. /* A typed pointer */ void *ptr_B.Why pointer ? address.globaledgesoft. } Embedded  Pointers are needed for accessing the . Telecom www.

printf(“%d”.a[5]).Pointer used as array Wireless Telecom www.com Embedded If we access array elements.globaledgesoft. int a[3] = {1. Output ???  Arrays don't have bounds checking  .2.3}. it is internally accessed only by using pointers arr[i] == *(arr + i).

Array of pointer Telecom www.com Wireless a 2-D array of chars : char array[10][10]. we can implement our array of strings as an array of pointers : char *array[3] = {“world”. ”heaven”.globaledgesoft.  Instead.  While swapping the string internally the pointers are swapped Embedded  We could implement an array of strings as . ”bye”}.

globaledgesoft. **ptr = &p. a = 1.com . **ptr. P = &a.Pointer to Pointer pointer Embedded  Pointer having the address of another Wireless Telecom Int *p. www.

*ptr = 'a'.globaledgesoft.com Wireless Char *ptr = &ch. Char *const ptr = &ch.value is constant const* int *const p .// error .address is constant  Char ch = 'c'. Ptr = &c //error . Ptr = &c.Constant pointer & pointer to constant Telecom www. . Const char *ptr = &ch. c.//constant pointer to a  constant integer Embedded  Char ch.

com Embedded Null pointer It points to nothing.globaledgesoft. when tried to dereference it causes error *p = NULL.States of pointer Wireless Telecom www. Void pointer (void*) this indicates that it can point to any datatype void *p. . Wild pointer pointer that doesn't point anything valid int *p.

P CR-08 Embedded Wireless Telecom .Complicated Declarations Ravichandran.

globaledgesoft.  Then read the left of the identifier until you find the open parantheses '(' . .Complicated Declarations  Then read the right of the identifier until Telecom www. Embedded  Rules to Read complicated Declarations  Start reading from the identifiers.  Then jump from that parantheses and follow the second and third step till the whole declaration completes.com Wireless you find the close parantheses ')' .

com Wireless an integer. P is a pointer to  Int (*p) (char) function takes char as arg and returns an integer.  Int * ( * ( *p) (int)) [10] P is a pointer to function that takes int as an argument and returns a pointer to an array of 10 pointers to integers. Embedded  Int *p.Examples P is a pointer to Telecom www. P is a pointer to  Int **p. pointer to an integer. .globaledgesoft.

ow-to-interpret-complex-C-Cdeclarations#contents Wireless  http://www.RITCHIE.References: W.com/Articles/7042/H Embedded  The C programming Language By BRIAN Telecom www.KERNIGHAN.globaledgesoft.com .codeproject.DENNIS M.

STRUCTURES Rajalakshmi Embedded Wireless Telecom .

globaledgesoft.com .Table of Contents Embedded  Basics of structure  Structure and functions  Arrays of structure  Pointer to structure  Padding and Packing Wireless Telecom www.

 Members can be referred using '. }.globaledgesoft.  Eg: struct point{ int x.' operator structure-name. char y.member  Structures can be nested .Basics of Structure Telecom www. Embedded  Structure is a collection of same or . possibly of different type.com Wireless different data types.  Instance of structure can be created as struct structure -name instance.

passing a pointer is more efficient.com Wireless different ways  Can pass members separately  Pass entire structure  Pass Pointers  If large structure is to be passed .Structures and Functions Telecom www. Embedded  Structures can be passed to function in 3 .globaledgesoft.  Pointers to structure can access the members in structure using ->operator.

 Eg: struct student{ char *name. }. Embedded  Array of structure is nothing but collection . struct student student_details[10].  Array of structures are used when multiple record of same structure has to be stored.com Wireless of structure.  This is also called structure array.globaledgesoft.Arrays of structures Telecom www. int rollno.

Pointers to structure Wireless function may not be efficient.particularly when structure is large.  We can eliminate is excessive movement of data by passing the pointer to structure to the functions.globaledgesoft. Embedded  Passing and returing the structure to a Telecom www.com .

com Wireless requirement. Embedded  Every datatype will have alignment .  Because of the alignment requirement of data type .  Processor will have processing word length as that of data bus. char b.Padding Telecom www.globaledgesoft. }x.  Structures are used as data pack.  Eg struct padding{ int a.each element has to be naturally aligned.

globaledgesoft. Embedded  Sometimes it is mandatory to avoid the .  Eg: #pragma pack(push. Int a. }x.com Wireless padded bytes  In such case packing is used  Performance in less compared to padding  This can be achived with help of pragma pack.1) Struct stack{ char c.packing Telecom www.

org/structure-member-alignm ent-padding-and-data-packing/ http://ee.edu/~tep/EE160/Book/chap12/subsectio n2.com .Kernighan and Dennis M.1.1.hawaii.  http://www.html w.globaledgesoft.Ritchie Wireless  The c programming language by Brain Embedded REFERENCES: Telecom www.4.geeksforgeeks.

STRUCTURES & UNIONS MONICA C CR-8 Embedded Wireless Telecom .

com .Table of content Embedded  Self-Referential structure  Typredef  Union  Bit-fields Wireless Telecom www.globaledgesoft.

stack.globaledgesoft. }  It is used in data structure such as binary tree. linked list. Struct list{  int data. Embedded  Structure that contains the reference .Self-Referential structure Telecom www.com Wireless to data of same type as themselves. queue etc. Struct list *next.  It is also called as RECURSIVE DATA STRUCTURES.

Typedef Telecom www. the name “UI” is a synonym for unsigned int.com Wireless create new data type.  In the above example.e) it does not .globaledgesoft. it adds a new name for some existing data type. Embedded  To create new data type (i. UI a.  Example: typedef unsigned int UI.

Struct list *next..globaledgesoft...com Wireless typedef struct list{ int data.} Embedded  Example: .. }list..}  We can change the above function as List create(){.  Instead of using Struct list create(){....Typedef Telecom www...

globaledgesoft. Embedded  Union provide a way to manipulate .Union Telecom www. float fnum. char ch.com Wireless different kinds of data in a single area of storage  Syntax :  Union example{ int num. }ex.

.  Union may occur within structures.com Wireless fnum . num .  Using pointers: union_name->member. Embedded  In the above example.member. ch are stored in the same place regardless of its type.globaledgesoft.  Members of the union can be accessed as union_name.Union Telecom www.

}flag.Bit-fields Telecom www. Unsigned int sign:1. Instead of using 4bytes for integer One bit is used.com Wireless at a premium  Example: Struct bit{ Unsigned int flag:1.globaledgesoft. Embedded  Bit-fields are used where storage space is .  In the above exmaple.

soe.Kernighan and Dennis M.com/vlc/mod/pag Embedded  http://classes.com .ucsc.opengurukul.edu/cmps203/Sprin www.php?id=2905  The C Programming Language by Brain Telecom W.Ritchie Wireless  http://www.References: g99/supplements/javaLists/ e/view.globaledgesoft.

FILES Embedded Wireless Telecom .

globaledgesoft.Table of Contents Wireless  File Operations  Reading and Writing with files Embedded  What is a file?  Accessing a file Telecom www.com .

Telecom www.globaledgesoft.  C uses a structure called FILE to store the attributes of a file.What is a file? Embedded Wireless  A file is a collection of related data as a single unit.com .  Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down.

 Read or write the data. Telecom www.globaledgesoft.  Close the file.  Open the file associating the pointer with the file name.com .Accessing a file Embedded Wireless  Create a pointer variable to the FILE structure: FILE *fp.

File Operations Wireless Telecom www.close a file opened  fread .com Embedded  fopen .read from a file  fwrite .specify how its opened (read/write) and type (binary/text)  fclose .tell you where the file pointer is located.write to a file  fseek .  ftell .globaledgesoft.move a file pointer to somewhere in a file.open a file. .

globaledgesoft. “mode”).com Telecom MEANING Wireless MODE Embedded Syntax: filepointer=fopen(“filename”.File Open r Open a existing file in read mode  If file does not exist error returned w Open a new file in write mode  If the file exists its contents will be erased a Open a new (or) existing file in append mode r+ Open for reading and writing (returns error if file does not exist) w+ Open for reading and writing (overwrites if file exists) a+ Open for reading and appending www.  File Opening modes  .

Writing to Files Wireless Telecom www.  fputs .  fwrite – writes a specified number of equally sized data  Syntax: size_t fwrite(const void *ptr. fptr). .  fputc – write a single character  Syntax: fputc(character. size_t n. filepointer).variables). size_t size.writes a string  Syntax: fputs(“String\n”.com Embedded  fprintf – writes multiple variables  Syntax:fprintf(fptr. filepointer).globaledgesoft.“string”.

size_t number_of_elements.globaledgesoft.  fgets – reads a string of n chars  Syntax: fgets(char *str. fileptr). number.  fread – reads a specified number of equally sized data elements  Syntax: size_t fread(void *ptr.identifiers). filepointer).com Embedded  fscanf – reads multiple variables  Syntax:fscanf(fp. size_t size.  fgetc – reads a single character  Syntax: character = fgetc(fileptr). .Reading from files Wireless Telecom www.“string”.

fseek(). long int offset.  ftell() .returns the current position of file pointer  Syntax: long int ftell(filepointer).moves the file pointer to the beginning of the file  Syntax: frewind(filepointer). ftell(). int origin).  frewind() . .globaledgesoft.sets the filepointer to the specified position in the file  Syntax: int fseek(filepointer.com Embedded  fseek() . frewind() Wireless Telecom www.

com .closes the file after finishing all the operations on file  Syntax – fclose(filepointer).Closing Files Embedded Wireless  fclose() .closes all the open files and return number of files closed  Syntax: int fcloseall() Telecom www.  fcloseall() .globaledgesoft.

Compiler Sampath N Embedded Wireless Telecom .Compilation Process Preprocessor.

globaledgesoft.com .Table of Contents Embedded  Overview  Compilation Stages Wireless Preprocessor Compiler Telecom www.

com .globaledgesoft.What is Compilation? program in one language (source language) into an equivalent program in another language compiler Target program Wireless Source program Embedded  Compilation is a process that translates a Telecom Error message www.

com .globaledgesoft.Complete Compilation Process Embedded Wireless Telecom www.

i) Embedded  The extension of preprocessed file is .globaledgesoft.  Expanding macros  Inclusion of header files  Comment Removal  Conditional compilation (gcc -E filename.c > filename.com Wireless -E command  Preprocessor performs following operations prior to compilation.Preprocessor Telecom www.i  It can be obtained by compiling code with .

com Telecom Semantic Analysis and Intermediate Code Generation Code Optimization Wireless Tokens Embedded Source program (character stream) .globaledgesoft.Compiler Intermediate code Scanner (lexical analysis) Parser (syntax analysis) Parse tree Modified intermediate form Target Code Generation Assembly code www.

Scanner: Lexical Analysis Wireless tokens  Grouping characters into non-separatable units (tokens)  Changing a stream to characters to a stream of tokens Embedded  Lexical analysis breaks up a program into Telecom www.globaledgesoft.com .

Memory occupied.com Wireless program together with all the attributes of each identifier  For variables typical attributes include Type.Symbol Table Telecom www. Scope  For functions typical attributes include  Number and type of arguments  Method of passing each argument  Type of value returned Embedded  A symbol table is a data structure  It containing all the identifiers of a source .globaledgesoft.

globaledgesoft.Parser: Syntax Analysis Telecom id1 + * id2 id3 Wireless the grammatical specification of the language and generates the syntax tree  Example for Syntax tree (Parse tree) Pos = init + rate *:=60  id1 = id2 + id3 * const Embedded  Checks whether the token stream meets 60 www.com .

.globaledgesoft. symbol table www. One of the most widely used intermediate code is TAC (Three Address Code).Sematic Analysis and Intermediate Code Generation  Semantic analysis is applied by a compiler Embedded  After sematic analysis intermediate code is Wireless to discover the meaning of a program by analyzing its parse tree.com Telecom generated.

 Common optimizations include  Removing redundant identifiers  Removing unreachable sections of code  Identifying common expressions  Unfolding loops  Eliminating procedures Embedded  The code optimization is required to .Code Optimization Telecom www.com Wireless produce an efficient target code.globaledgesoft.  An optimizer attempts to improve the time and space requirements of a program.

 The extension of preprocessed file is .  This assembly code is given as input to assembler.Target Code Generation Wireless assembly code.s  It can be obtained by compiling code with -S command (gcc -S filename.globaledgesoft.c) Embedded  The final stage of compiler is to generate Telecom www.com .

Compilation Process Assembler and Linker Embedded Wireless Telecom .

globaledgesoft.Table of Contents Wireless  Assembler  Overview  Object file format  Process for producing an executable file Embedded  Compilation process Telecom  Linker  Loader www.com .

data and instructions needed to place properly in memory.  Assembler translates assembly instructions and pseudo instructions into machine instructions.Assembler Telecom www.globaledgesoft.  It converts the decimal numbers given by the user to binary form.  Object files contains a combination of machine instructions.com Wireless language programs into object files. Embedded  Assembler converts assembly .

globaledgesoft.  Second pass : use information in the symbol table to produce machine code for each line..Assembler (contd.com ..) Wireless labels in a symbol table. Embedded  Assembler has two passes  First pass : reads each line and records Telecom www.

Data segment contains the binary representation of data in assembly file. Text segment contains machine instructions. Relocation info identifies instructions and data that depend on adsolute address.globaledgesoft.com references. Symbol table associates addresses with the external labels and lists unresolved www. Wireless  Object file describes the position and size of Embedded  Object file format . Debug info.Object file format Object header Text Segment Data Segment Relocation Information Symbol Table Debugging information    Telecom  files.

com Telecom Program library Wireless Assembler Embedded Source file .Process for producing .globaledgesoft.exe file www.exe file Object file Source file Assembler Object file Source file Assembler Object file Linker .

Linker Embedded Wireless Telecom Tool that gets seperate object file from assembler and merges those object file to form an executable file.  Determines the memory locations that each module should occupy and relocates its instructions by adjusting the absolute references.com  .  It performs three tasks  Finds library routines used by programs.  Resolves references among the files. www.globaledgesoft.

com .  Jumps to the startup routine that copies the program's arguments from the stack to registers and calls the program's main routine.exe file header to determine the size of the text and data segments.  Create new address space for program.globaledgesoft. www.Loader Embedded Wireless Telecom Steps involved :  Read .  Copies arguments passed to the program into stack.  Copies instructions and data into address space.

Stack Frame Embedded Wireless Telecom .

com .globaledgesoft.Table of Contents Embedded  Terminologies  Subroutine  Stack Frame Structure  Example Program  Stack Related Issues Wireless Telecom www.

com Wireless stack associated with one subroutine call.  Stack Pointer: register that contains the top of the stack.Terminologies Telecom www.  Frame Pointer: register that set to the address of the stack frame when a subprogram begins executing. Embedded  Stack Frame: collection of all data in the .globaledgesoft.

globaledgesoft.com . packaged as a unit.Subroutine program instructions that perform specific task. a Embedded  Subroutine : a subroutine is a sequence of Wireless Telecom www.

Stack Frame Structure arg2 arg1 frame pointer old sp local2 Stack pointer local3 www.globaledgesoft.com Telecom local1 Wireless return address Embedded arg3 .

} Telecom www. p3 ) int p1. p2. { int v1. foo( p1. p2.com . p3). v2 .globaledgesoft. } main( ) { foo( p1. p3. p2 =2 . p3 = 3.v3.Example Program Embedded Wireless int p1 = 1. return 0. p2.

com Telecom p3 Wireless return addr Static Memory -P1 500 1 -P2 502 2 -P3 504 3 Embedded 100: 102:SP-> 103: 106: 108:FP-> 110: 112: 114: 116 118: 120: 122: 124 .globaledgesoft.Stack Structure v3 v2 v1 Old FP p1 p2 Old FP FP return addr Registers SP 102 108 argv argc www.

Stack Frame Issues is no way for the called routine to know whether the arguments pushed on the stack are of the correct type. Wireless  The Embedded  There . www.com Telecom called routine cannot know whether the calling routine pushed the correct number of arguments onto the stack.globaledgesoft. it just assumes that they are there.

..com ..globaledgesoft.. Embedded  If a routine can be told how many and what Telecom www. it can be passed a variable number of argument. Wireless type of arguments to expect on the stack..Cont.

A Embedded Wireless Telecom .THE C PREPROCESSOR Girija Pretha.

Table of Contents Embedded  C Preprocessor  Preprocessing Phases  Conditional compilation Wireless  Header file inclusion  Macro expansion/substitution Telecom www.globaledgesoft.com .

com Wireless compilation process.  It is a Macro processor that is used automatically by c compiler to transform program before compilation.C Preprocessor Telecom www.globaledgesoft.  It allows to define macros which are abbreviations of larger constructs Embedded  Preprocessor is the first stage in .  Preprocessor instructs the compiler to do some tasks before actual compilation.

com Telecom   expanded code compiled code cc1 Wireless source program . …) www. #ifdef.Preprocessing.globaledgesoft. Embedded C compiler (e.g..... gcc) cpp (C preprocessor) (C compiler) expand some kinds of characters discard whitespace and comments  each comment is replaced with a single space  process directives:  file inclusion (#include)  macro expansion (#define)  conditional compilation (#if.

Preprocessing Phases Embedded  Phases in preprocessing are Wireless Header File inclusion Macro expansion Conditional Compilation Comment line removal Telecom www.com .globaledgesoft.

#include "file" The search path is expanded to include the current source directory and searches in standard path if file not found in current directory.Header File Inclusion Wireless Telecom www.globaledgesoft.com Embedded #include <file> • The file is searched for in the standard compiler include paths. .

Object macros : PI 3.Macro Expansion Telecom www.globaledgesoft. Objects macros are used to avoid hard coding in the program Embedded  Identifiers defined as macro are directly .14 Function macros : SQR(a) a*a This must not have whitespace between SQR and '('. If given they are expanded from '(' in source code.com Wireless expanded in source code.

 Conditions can be arithmetic expression or macro is defined or not. `#if' Basic conditionals using `#if' and `#endif'.Conditional Compilation Telecom www. `#else' Including some text if the condition fails. on some conditions. `#elif' Testing several alternative possibilities.com Wireless of the program to be ignored during compilation.globaledgesoft. Embedded  Conditional is a directive that allows a part .

com .PI).Program for macro Embedded Wireless Telecom #include<stdio. printf("Value of macro is%d".h> #ifndef PI #define PI 3. } www. return 0.globaledgesoft.14 #endif int main() { /*This is the macro example*/ printf("\nThis is macro example\n").

c" # 1 "/usr/include/stdio. return 0.h" 1 3 4 # 28 "/usr/include/stdio. printf("Value of macro is%d".Source code after preprocessing Comments are replaced with blank lines www.com Telecom Macro is Substituted with its value.h" 3 4 int main() { . Wireless printf("\nThis is macro example\n").14).c" # 1 "<built-in>" # 1 "<command line>" # 1 "test.globaledgesoft.3. } Embedded # 1 "test.

Memory Layout Embedded Wireless Telecom .

globaledgesoft.Table of Contents Embedded Wireless  Text Segment  Initialized Data Segment  Uninitialized Data Segment (bss)  Heap  Stack Telecom www.com .

Memory layout of C Program Stack Uninitialized Data Segment (bss) Text Segment www.com Telecom Initialized Data Segment Wireless Heap Embedded Command Line Arguments And Global Variables .globaledgesoft.

com Wireless which contains executable Instructions.  Prevent machine codes from being over written by stack or heap overflow. it is kept read only.  It can be accessed using function pointers. . Embedded  Text Segment is a read Only (RO) part.Text Segment Telecom www.globaledgesoft.

Telecom www. Embedded  It is also called as Data Segment  It contains static and global variables Int a = 10. We can do read Wireless and write in this part. Static int a = 10.Initialized Data Segment  It is not a read only part.com .globaledgesoft.

globaledgesoft. Embedded  It is also called as BSS.  Lifetime of uninitialized data is the complete execution time of the program. Int a. www.  Data in the BSS segment are initialized to zero.Uninitialized Data Segment Wireless variables.  It contains uninitialized static and global Telecom Static int a.com .

 Its address space grows from lower to higher. calloc(). realloc() can be used to perform dynamic memory allocation.Heap Wireless Telecom www.  .com Embedded Dynamic memory allocation takes place at the heap segment.  malloc().globaledgesoft.  The Heap area is shared by all shared libraries an dynamically loaded modules in a process.

 Stack segment grows from highernumbered address to lower numbered address.Stack Embedded Wireless Telecom All local variables stored under stack segment.  When a function is called memory will be allocated for its local variables in a new stack frame. } www. Int add() { Int a = 10. b = 10.globaledgesoft.com  .

org/memory-layout-of-c-program/ Telecom www.com .globaledgesoft.html Embedded http://www.References Wireless http://see-programming.blogspot.in/2013/10/memory-layoutof-c-program.geeksforgeeks.

com .Embedded Wireless Telecom www.globaledgesoft.