You are on page 1of 149

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

A simple C program
Embedded

#include<stdio.h>

Wireless

int main()
{
printf(\nHello, World);

Telecom

www.globaledgesoft.com

BASIC DATA TYPES

short int

Int

long int
unsigned long
int

-32,768(-215)

32,767(215-1)

65,535(216-1)

-2,147,483,648(-231)

2,147,483,648(231-1)

4,294,967,295

-2,147,483,648(-231)

2,147,483,648(231-1)

4,294,967,295
www.globaledgesoft.com

Telecom

unsigned int

Largest Value

Wireless

unsigned
short int

Smallest Value

Embedded

Type (32 bit)

BASIC DATA TYPES(CONTD..)

char

Smallest Value

Largest Value

-128

127

-3.4E +38

3.4E+38

double

-1.7E+308

1.7E+308

Wireless

float

Embedded

Type (32 bit)

Telecom
www.globaledgesoft.com

Variables

www.globaledgesoft.com

Telecom

The general form of declaring a variable


is,
Datatype variable_list;
Eg:
int var; //declaration
var = 5;//assignment
int var = 5; //initialization

Wireless

All variables must be declared before use.

Embedded

Variable is a named location in memory


that is used to hold a value.

Operators

Telecom

www.globaledgesoft.com

Wireless

Arithmetic operators
Relational and Logical operators
Bitwise operators
Increment and Decrement operators
Conditional operators

Embedded

Control Flow

Iteration statements
while (expr) stmt;
for (expr1;expr2;expr3) stmt;
do stmt while expr;
www.globaledgesoft.com

Telecom

Wireless

Selection statements
if (expr) stmt;
if (expr) stmt1 else stmt2;
switch (expr) {case ... default }

Embedded

Array and Pointer

Telecom

www.globaledgesoft.com

Wireless

Pointers:
A pointer is a variable that holds the
address of another variable.
Eg: int *ptr; //declaring a pointer variable
Int *ptr = &a; // initialization

Embedded

Array:
An array is a collection of variables of
the same type that are referred through a
common name.
syntax:datatype var_name[size];

Functions
Building blocks of c .

www.globaledgesoft.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.

Embedded

Structure and Union

Wireless

Union:
A union is a memory location that is
shared by different types of variables.

Embedded

Structures:
Structure is a collection of same or
different data type, grouped together in a
single name for
convenient handling.

Telecom

www.globaledgesoft.com

Files

Files must be opened before being


accessed.

For files you want to read or write, you


need a file pointer,
Eg: FILE *fp;

Wireless

A file is viewed as a stream of bytes.

Embedded

www.globaledgesoft.com

Telecom

Data Types and


Expressions

Embedded

Wireless

Telecom

Table of Contents

Wireless
Telecom

www.globaledgesoft.com

Embedded

Introduction
Data Types in C
Built-in Data Types
Derived Data Types
Expression
Assignment Operator and Expression
Conditional Expression
Storage class

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.globaledgesoft.com

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.com

Telecom

Derived data types

Wireless

Built-in data types

Embedded

In C we have two kind of Data types

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.globaledgesoft.com

Built-in Data Type(cont)

Wireless
Telecom

2 bytes
range -32,768 to 32,767 or
0 to 65,535(unsigned)
Float : size 4 bytes
range 1.2E-38 to 3.4E+38
precision 6 decimal places
Double : size 8 bytes
range 2.3E-308 to 1.7E+308
precision 15 decimal places
Long Double : size 10 bytes
range 3.4E-4932 to 1.1E+4932
precision 19 decimal places
www.globaledgesoft.com

Embedded

Short : size

Derived Data types

Telecom

struct structname

{
Variables
}structure object;

Wireless

Syntax

Embedded

Array : it is a collection of homogeneous


elements of given data type
Example: int a[10]; A[] is array subscript
Structure : it is collection of heterogeneous
elements of all basic data types. it
allocates memory for all data types inside
a structure

www.globaledgesoft.com

Derived Data types(cont)

variable. Size is 4 bytes

Example

int *p;
www.globaledgesoft.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;

Embedded

Union :it is also collection of heterogeneous

Expression

Wireless
Telecom

variables, 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*bc
Expression will be evaluated based on
precedence of operator
Highest priority = * / %
www.globaledgesoft.com
Lowest priority = + -

Embedded

An expression is a combination of

Conditional Expression
evaluated

expr1 ? expr2 : expr3

Example

z = (a > b) ? a : b;

evaluated

else expression 3 will be evaluated

www.globaledgesoft.com

Telecom

If expression 1 is true expression 2 will be

Wireless

Syntax

Embedded

Based on condition expression will be

Storage class
Embedded
Wireless

Topics :

Automatic variables

External variables

Static variables

Register variables

Telecom
www.globaledgesoft.com

Auto
Auto declare inside a function in which
they are to be utilized.
eg. int number; auto int number;

Embedded

This variables are private(local) to the


function in which they are declared.

Wireless

www.globaledgesoft.com

Telecom

Variables declared inside a function


without storage class specification is, by
default, an automatic variable.

static

Static variables are initialized only once,


when the program is compiled.

www.globaledgesoft.com

Telecom

It may be of external or internal type


depending on the place of there declaration.

Wireless

It is declared using the keyword static like


static int x;

Embedded

The value of static variables persists until


the end of the program.

Register

www.globaledgesoft.com

Telecom

Dont try to declare a global variable as


register. Because the register will be
occupied during the lifetime of the program.

Wireless

C will automatically convert register


variables into nonregister variables once the
limit is reached.

Embedded

Storage variables are stored in one of the


machines register and are declared using
register keyword.
eg. register int c

Extern

Telecom

www.globaledgesoft.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.

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

Table of Contents

www.globaledgesoft.com

Telecom

Operators in C
Arithmetic operators
Increment/decrement operators
Relational operators
Logical operators
Conditional operator
Bitwise operators
Special operators

Wireless

Embedded

Introduction

Introduction

Wireless
Telecom

www.globaledgesoft.com

Embedded

Operators are symbols which take one


or more operands or expressions and
perform arithmetic or logical
computations.
Eg: a=b+c; here '=' and '+' are
operators and a,b,c are operands
C program provides wide variety of
operators

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

Logical Operators
There are 3 logical operators in C
language. They are, logical AND (&&),
logical OR (||) and logical NOT (!).
Example

&&

Logical AND

x&& y

||

LOGICAL OR

x||y

Logical NOT

!(x&&y)
www.globaledgesoft.com

Telecom

Operation

Wireless

Operator

Embedded

Conditional Operators

Telecom

Working of the ? Operator:


Ex: m=2;
n=3
r=(m>n) ? m : n;

Wireless

Embedded

Conditional operators return one value if


condition is true and returns another value
is condition is false.
Syntax : exp1 ? exp2 : exp3
Where exp1,exp2 and exp3 are expressions

www.globaledgesoft.com

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.globaledgesoft.com

Bitwise operators contd..


Embedded

Left Shift:
Shift n bits to left
Eg: a<<=3;

Wireless
Telecom

Right Shift
Shift n bits to right
Eg:a>>=5;

www.globaledgesoft.com

Special operators
There are few other operators supported
by C Language.
Example

sizeof()

Returns the size


of a variable

sizeof(a);
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

Used to link
related
expression
together

int a,b,c;

www.globaledgesoft.com

Telecom

Description

Wireless

Operator

Embedded

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

Table of Contents

Wireless
Telecom

www.globaledgesoft.com

Embedded

If else
Else if
Switch
Loops While,For & Do While
Break
Continue
Goto
Labels

If else

Telecom

www.globaledgesoft.com

Wireless

if ( Expression )
statement1;
else
statement2;
Expression May Be checked with
Conditions.

Embedded

Used To Express Decisions.


Syntax :

Else - if
decisions .

Telecom

www.globaledgesoft.com

Wireless

if(Expression1) s1;
Else if (Expression2)s2;
Else s3;
Control flows in order from top.
If expression satisfies condition,
statements within that condition gets
executed.

Embedded

Multiway
Syntax:

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

For

Wireless
Telecom

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

Embedded

Syntax :

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

Table of Contents
Embedded
Wireless

Introduction
What are function pointers .?
Definition
Need of function pointers
Assign and call using function pointers
Array of function pointers.

Telecom
www.globaledgesoft.com

Introduction

Telecom

www.globaledgesoft.com

Wireless

of register has an address.


We can reference variables of the type
char, int, float, etc., through their address
(ie ., by using pointers).
Pointers can also point to c functions.
While many programming languages
support the concept of pointers to data,
only a few enable you to define pointers to
code -- that is, pointers that point to
functions

Embedded

Every type of variables with the exception

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 functions name
assign an address to the function pointer
int (*funcPointer) (int, char, int);

Telecom

www.globaledgesoft.com

Wireless

int welcome ( int a, char b, int c){


printf( Welcome to my presentation);
return a+b+c;
}
funcPointer= welcome; //assignment
funcPointer=&welcome; //alternative using
address operator

Embedded

It is optional to use the address operator &

Call using function pointers


There are two alternatives
* Use the name of the function pointer
* Can explicitly dereference it

Embedded

int (*funcPointer) (int, char, int);

Wireless

www.globaledgesoft.com

Telecom

// calling a function using function pointer


answer= funcPointer (7, A , 2 );
answer=(* funcPointer) (7, A , 2 );

Array of function pointers


pointers to data therefore we can have
arrays of pointers to functions

www.globaledgesoft.com

Telecom

suppose that were writing a program


that displays a menu of commands for the
user to choose from. We can write functions
that implement these command then store
pointers to the functions in an array.

Wireless

This offers the possibility to select a


function using an index
Eg.

Embedded

C treats pointers to functions just like

Cont...

If the user selects a command between 0


and 6,then,we can subscript the file_cmd
array to find out which function to call

Wireless

Embedded

void (*file_cmd[]) (void) =


{ new_cmd, open_cmd, close_cmd,
save_cmd ,
save_as_cmd, print_cmd,exit_cmd };

Telecom

file_cmd[n]();

www.globaledgesoft.com

POINTERS AND ARRAYS


Kiruthika . N

Embedded

Wireless

Telecom

Table of Contents

www.globaledgesoft.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

Define pointer
A pointer is a variable whose value is the
address of another variable, i.e., direct
address of the memory location.

Embedded

Wireless

Int a = 3;
Int *ptr = &a;

Telecom
www.globaledgesoft.com

Why pointer ?

address.

Telecom

www.globaledgesoft.com

Wireless

#include<stdio.h>
int main()
{
int *ptr_A; /* A typed pointer */
void *ptr_B; /* A untyped pointer */
return 0;
}

Embedded

Pointers are needed for accessing the

Pointer used as array

Wireless
Telecom

www.globaledgesoft.com

Embedded

If we access array elements, it is


internally accessed only by using pointers
arr[i] == *(arr + i);
int a[3] = {1,2,3};
printf(%d,a[5]);
Output ???

Arrays don't have bounds checking

Array of pointer

Telecom

www.globaledgesoft.com

Wireless

a 2-D array of chars :


char array[10][10];
Instead, we can implement our array of
strings as an array of pointers :
char *array[3] = {world, heaven,
bye};
While swapping the string internally the
pointers are swapped

Embedded

We could implement an array of strings as

Pointer to Pointer

pointer

Embedded

Pointer having the address of another

Wireless
Telecom

Int *p, **ptr, a = 1;


P = &a;
**ptr = &p;

www.globaledgesoft.com

Constant pointer & pointer to constant

Telecom

www.globaledgesoft.com

Wireless

Char *ptr = &ch;


Ptr = &c;
Char *const ptr = &ch;
Ptr = &c //error ,address is constant
Char ch = 'c';
Const char *ptr = &ch;
*ptr = 'a';// error ,value is constant
const* int *const p ;//constant pointer to a
constant integer

Embedded

Char ch, c;

States of pointer

Wireless
Telecom

www.globaledgesoft.com

Embedded

Null pointer
It points to nothing, when tried to
dereference it causes error
*p = NULL;
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;

Complicated
Declarations
Ravichandran. P
CR-08
Embedded

Wireless

Telecom

Complicated Declarations

Then read the right of the identifier until

Telecom

www.globaledgesoft.com

Wireless

you find the close parantheses ')' .


Then read the left of the identifier until you
find the open parantheses '(' .
Then jump from that parantheses and
follow the second and third step till the
whole declaration completes.

Embedded

Rules to Read complicated Declarations


Start reading from the identifiers.

Examples
P is a pointer to

Telecom

www.globaledgesoft.com

Wireless

an integer.
P is a pointer to
Int **p;
pointer to 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;

References:
W.KERNIGHAN,DENNIS M.RITCHIE.

ow-to-interpret-complex-C-Cdeclarations#contents

Wireless

http://www.codeproject.com/Articles/7042/H

Embedded

The C programming Language By BRIAN

Telecom
www.globaledgesoft.com

STRUCTURES
Rajalakshmi

Embedded

Wireless

Telecom

Table of Contents
Embedded

Basics of structure
Structure and functions
Arrays of structure
Pointer to structure
Padding and Packing

Wireless
Telecom
www.globaledgesoft.com

Basics of Structure

Telecom

www.globaledgesoft.com

Wireless

different data types, possibly of different


type.
Eg: struct point{
int x;
char y;
};
Instance of structure can be created as
struct structure -name instance;
Members can be referred using '.' operator
structure-name.member
Structures can be nested .

Embedded

Structure is a collection of same or

Structures and Functions

Telecom

www.globaledgesoft.com

Wireless

different ways
Can pass members separately
Pass entire structure
Pass Pointers
If large structure is to be passed ,passing a
pointer is more efficient.
Pointers to structure can access the
members in structure using ->operator.

Embedded

Structures can be passed to function in 3

Arrays of structures

Telecom

www.globaledgesoft.com

Wireless

of structure.
This is also called structure array.
Eg: struct student{
char *name;
int rollno;
};
struct student student_details[10];
Array of structures are used when multiple
record of same structure has to be stored.

Embedded

Array of structure is nothing but collection

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.

Embedded

Passing and returing the structure to a

Telecom
www.globaledgesoft.com

Padding

Telecom

www.globaledgesoft.com

Wireless

requirement.
Processor will have processing word length
as that of data bus.
Structures are used as data pack.
Because of the alignment requirement of
data type ,each element has to be
naturally aligned.
Eg struct padding{
int a;
char b;
}x;

Embedded

Every datatype will have alignment

packing

Telecom

www.globaledgesoft.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.
Eg: #pragma pack(push,1)
Struct stack{
char c;
Int a;
}x;

Embedded

Sometimes it is mandatory to avoid the

http://www.geeksforgeeks.org/structure-member-alignm
ent-padding-and-data-packing/
http://ee.hawaii.edu/~tep/EE160/Book/chap12/subsectio
n2.1.1.4.html

w.Kernighan and Dennis M.Ritchie

Wireless

The c programming language by Brain

Embedded

REFERENCES:

Telecom
www.globaledgesoft.com

STRUCTURES & UNIONS


MONICA C
CR-8

Embedded

Wireless

Telecom

Table of content
Embedded

Self-Referential structure
Typredef
Union
Bit-fields

Wireless
Telecom
www.globaledgesoft.com

Self-Referential structure

Telecom

www.globaledgesoft.com

Wireless

to data of same type as themselves.


It is also called as RECURSIVE DATA
STRUCTURES.
Struct list{

int data;
Struct list *next;
}
It is used in data structure such as binary
tree, linked list, stack, queue etc.

Embedded

Structure that contains the reference

Typedef

Telecom

www.globaledgesoft.com

Wireless

create new data type, it adds a new name


for some existing data type.
Example:
typedef unsigned int UI;
UI a;
In the above example, the name UI is a
synonym for unsigned int.

Embedded

To create new data type (i.e) it does not

Typedef

Telecom

www.globaledgesoft.com

Wireless

typedef struct list{


int data;
Struct list *next;
}list;
Instead of using
Struct list create(){......}
We can change the above function as
List create(){......}

Embedded

Example:

Union

Telecom

www.globaledgesoft.com

Wireless

different kinds of data in a single area of


storage
Syntax :
Union example{
int num;
float fnum;
char ch;
}ex;

Embedded

Union provide a way to manipulate

Union

Telecom

www.globaledgesoft.com

Wireless

fnum , ch are
stored in the same place regardless of its
type.
Members of the union can be accessed as
union_name.member;
Using pointers:
union_name->member;
Union may occur within structures.

Embedded

In the above example, num ,

Bit-fields

Telecom

www.globaledgesoft.com

Wireless

at a premium
Example:
Struct bit{
Unsigned int flag:1;
Unsigned int sign:1;
}flag;
In the above exmaple, Instead of using
4bytes for integer
One bit is used.

Embedded

Bit-fields are used where storage space is

References:
g99/supplements/javaLists/

e/view.php?id=2905

The C Programming Language by Brain

Telecom

W.Kernighan and
Dennis M.Ritchie

Wireless

http://www.opengurukul.com/vlc/mod/pag

Embedded

http://classes.soe.ucsc.edu/cmps203/Sprin

www.globaledgesoft.com

FILES
Embedded

Wireless

Telecom

Table of Contents

Wireless

File Operations
Reading and Writing with files

Embedded

What is a file?
Accessing a file

Telecom
www.globaledgesoft.com

What is a file?
Embedded
Wireless

A file is a collection of related data as a


single unit.
Computers store files to secondary
storage so that the contents of files
remain intact when a computer shuts
down.
C uses a structure called FILE to store the
attributes of a file.

Telecom
www.globaledgesoft.com

Accessing a file
Embedded
Wireless

Create a pointer variable to the FILE


structure: FILE *fp;
Open the file associating the pointer with
the file name.
Read or write the data.
Close the file.

Telecom
www.globaledgesoft.com

File Operations

Wireless
Telecom

www.globaledgesoft.com

Embedded

fopen - open a file- specify how its opened


(read/write) and type (binary/text)
fclose - close a file opened
fread - read from a file
fwrite - write to a file
fseek - move a file pointer to somewhere
in a file.
ftell - tell you where the file pointer is
located.

File Open

Open a existing file in read mode


If file does not exist error returned

Open a new file in write mode


If the file exists its contents will be erased

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.globaledgesoft.com

Telecom

MEANING

Wireless

MODE

Embedded

Syntax:
filepointer=fopen(filename, mode);

File Opening modes

Writing to Files

Wireless
Telecom

www.globaledgesoft.com

Embedded

fprintf writes multiple variables


Syntax:fprintf(fptr,string,variables);
fputc write a single character
Syntax: fputc(character, filepointer);
fputs - writes a string
Syntax: fputs(String\n, filepointer);
fwrite writes a specified number of
equally sized data
Syntax: size_t fwrite(const void *ptr, size_t
size, size_t n, fptr);

Reading from files

Wireless
Telecom

www.globaledgesoft.com

Embedded

fscanf reads multiple variables


Syntax:fscanf(fp,string,identifiers);
fgetc reads a single character
Syntax: character = fgetc(fileptr);
fgets reads a string of n chars
Syntax: fgets(char *str, number,
filepointer);
fread reads a specified number of
equally sized data elements
Syntax: size_t fread(void *ptr, size_t size,
size_t number_of_elements, fileptr);

fseek(), ftell(), frewind()

Wireless
Telecom

www.globaledgesoft.com

Embedded

fseek() - sets the filepointer to the


specified position in the file
Syntax: int fseek(filepointer, long int
offset, int origin);
ftell() - returns the current position of file
pointer
Syntax: long int ftell(filepointer);
frewind() - moves the file pointer to the
beginning of the file
Syntax: frewind(filepointer);

Closing Files
Embedded
Wireless

fclose() - closes the file after finishing all


the operations on file
Syntax fclose(filepointer);
fcloseall() - closes all the open files and
return number of files closed
Syntax: int fcloseall()

Telecom
www.globaledgesoft.com

Compilation Process
Preprocessor, Compiler
Sampath N

Embedded

Wireless

Telecom

Table of Contents
Embedded

Overview
Compilation Stages

Wireless

Preprocessor
Compiler

Telecom
www.globaledgesoft.com

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.globaledgesoft.com

Complete Compilation Process


Embedded
Wireless
Telecom
www.globaledgesoft.com

Preprocessor

Telecom

www.globaledgesoft.com

Wireless

-E command
Preprocessor performs following
operations prior to compilation.
Expanding macros
Inclusion of header files
Comment Removal
Conditional compilation
(gcc -E filename.c > filename.i)

Embedded

The extension of preprocessed file is .i


It can be obtained by compiling code with

Compiler
Intermediate code

Scanner
(lexical analysis)

Parser
(syntax analysis)
Parse tree

Modified intermediate form


Target Code
Generation
Assembly code

www.globaledgesoft.com

Telecom

Semantic Analysis and


Intermediate Code
Generation

Code Optimization

Wireless

Tokens

Embedded

Source program (character stream)

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

Symbol Table

Telecom

www.globaledgesoft.com

Wireless

program together with all the attributes of


each identifier
For variables typical attributes include
Type, Memory occupied, 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

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.globaledgesoft.com

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, symbol table

www.globaledgesoft.com

Telecom

generated. One of the most widely used


intermediate code is TAC (Three Address
Code).

Code Optimization

Telecom

www.globaledgesoft.com

Wireless

produce an efficient target code.


An optimizer attempts to improve the time
and space requirements of a program.
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

Target Code Generation

Wireless

assembly code.
This assembly code is given as input to
assembler.
The extension of preprocessed file is .s
It can be obtained by compiling code with
-S command (gcc -S filename.c)

Embedded

The final stage of compiler is to generate

Telecom
www.globaledgesoft.com

Compilation Process
Assembler and Linker

Embedded

Wireless

Telecom

Table of Contents

Wireless

Assembler
Overview
Object file format
Process for producing an
executable file

Embedded

Compilation process

Telecom

Linker
Loader

www.globaledgesoft.com

Assembler

Telecom

www.globaledgesoft.com

Wireless

language programs into object files.


Object files contains a combination of
machine instructions,data and
instructions needed to place properly
in memory.
Assembler translates assembly
instructions and pseudo instructions
into machine instructions.
It converts the decimal numbers
given by the user to binary form.

Embedded

Assembler converts assembly

Assembler (contd...)

Wireless

labels in a symbol table.


Second pass : use information in the
symbol table to produce machine code
for each line.

Embedded

Assembler has two passes


First pass : reads each line and records

Telecom
www.globaledgesoft.com

Object file format

Object
header

Text
Segment

Data
Segment

Relocation
Information

Symbol
Table

Debugging
information

Telecom

files.
Text segment contains machine instructions.
Data segment contains the binary
representation of data in assembly file.
Relocation info identifies instructions and data
that depend on adsolute address.
Symbol table associates addresses with the
external labels and lists unresolved
www.globaledgesoft.com
references. Debug info.

Wireless

Object file describes the position and size of

Embedded

Object file format

Process for producing .exe file


Object
file

Source
file

Assembler

Object
file

Source
file

Assembler

Object
file

Linker

.exe
file

www.globaledgesoft.com

Telecom

Program
library

Wireless

Assembler

Embedded

Source
file

Linker
Embedded
Wireless
Telecom

Tool that gets seperate object file from


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

Loader
Embedded
Wireless
Telecom

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

Stack Frame

Embedded

Wireless

Telecom

Table of Contents
Embedded

Terminologies
Subroutine
Stack Frame Structure
Example Program
Stack Related Issues

Wireless
Telecom
www.globaledgesoft.com

Terminologies

Telecom

www.globaledgesoft.com

Wireless

stack
associated with one subroutine
call.
Stack Pointer: register that contains the
top of the stack.
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

Subroutine

program instructions that perform


specific task, packaged as a unit.

Embedded

Subroutine : a subroutine is a sequence of

Wireless
Telecom
www.globaledgesoft.com

Stack Frame Structure

arg2
arg1

frame pointer

old sp

local2

Stack pointer

local3
www.globaledgesoft.com

Telecom

local1

Wireless

return address

Embedded

arg3

Example Program
Embedded
Wireless

int p1 = 1, p2 =2 , p3 = 3;
foo( p1, p2, p3 )
int p1, p2, p3;
{
int v1, v2 ,v3;
return 0;
}
main( )
{
foo( p1, p2, p3);
}

Telecom
www.globaledgesoft.com

Stack Structure
v3
v2
v1
Old FP

p1
p2

Old FP

FP

return addr

Registers
SP

102
108

argv
argc

www.globaledgesoft.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

Stack Frame Issues


is no way for the called routine to
know whether the arguments pushed on
the stack are of the correct type.

www.globaledgesoft.com

Telecom

called routine cannot know whether


the calling routine pushed the correct
number of arguments onto the stack, it
just assumes that they are there.

Wireless

The

Embedded

There

Cont......

Wireless

type of arguments to expect on the stack, it


can be passed a variable number of
argument.

Embedded

If a routine can be told how many and what

Telecom
www.globaledgesoft.com

THE C PREPROCESSOR
Girija Pretha.A

Embedded

Wireless

Telecom

Table of Contents
Embedded

C Preprocessor
Preprocessing Phases

Conditional compilation

Wireless

Header file inclusion


Macro expansion/substitution

Telecom
www.globaledgesoft.com

C Preprocessor

Telecom

www.globaledgesoft.com

Wireless

compilation process.
Preprocessor instructs the compiler to do
some tasks before actual compilation.
It is a Macro processor that is used
automatically by c compiler to transform
program before compilation.
It allows to define macros which are
abbreviations of larger constructs

Embedded

Preprocessor is the first stage in

Preprocessing....
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, #ifdef, )

www.globaledgesoft.com

Telecom

expanded
code

compiled
code

cc1

Wireless

source
program

Preprocessing Phases
Embedded

Phases in preprocessing are

Wireless

Header File inclusion


Macro expansion
Conditional Compilation
Comment line removal

Telecom
www.globaledgesoft.com

Header File Inclusion

Wireless
Telecom

www.globaledgesoft.com

Embedded

#include <file>
The file is searched for in the standard
compiler include paths.
#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.

Macro Expansion

Telecom

www.globaledgesoft.com

Wireless

expanded in source code.


Object macros : PI 3.14
Function macros : SQR(a) a*a
This must not have whitespace between
SQR and '('.
If given they are expanded from '(' in
source code. Objects macros are used to
avoid hard coding in the program

Embedded

Identifiers defined as macro are directly

Conditional Compilation

Telecom

www.globaledgesoft.com

Wireless

of the program to be ignored during


compilation, on some conditions.
Conditions can be arithmetic expression or
macro is defined or not.
`#if' Basic conditionals using `#if' and
`#endif'.
`#else' Including some text if the condition
fails.
`#elif' Testing several alternative
possibilities.

Embedded

Conditional is a directive that allows a part

Program for macro


Embedded
Wireless
Telecom

#include<stdio.h>
#ifndef PI
#define PI 3.14
#endif
int main()
{
/*This is the macro example*/
printf("\nThis is macro example\n");
printf("Value of macro is%d",PI);
return 0;
}
www.globaledgesoft.com

Source code after preprocessing

Comments are
replaced with blank
lines

www.globaledgesoft.com

Telecom

Macro is
Substituted with its
value.

Wireless

printf("\nThis is macro example\n");


printf("Value of macro is%d",3.14);
return 0;
}

Embedded

# 1 "test.c"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "test.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 28 "/usr/include/stdio.h" 3 4
int main()
{

Memory Layout

Embedded

Wireless

Telecom

Table of Contents
Embedded
Wireless

Text Segment
Initialized Data Segment
Uninitialized Data Segment (bss)
Heap
Stack

Telecom
www.globaledgesoft.com

Memory layout of C Program

Stack

Uninitialized Data Segment (bss)

Text Segment
www.globaledgesoft.com

Telecom

Initialized Data Segment

Wireless

Heap

Embedded

Command Line Arguments And Global


Variables

Text Segment

Telecom

www.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,

Initialized Data Segment

It is not a read only part. We can do read

Wireless

and write in this part.

Embedded

It is also called as Data Segment


It contains static and global variables

Int a = 10;
Static int a = 10;

Telecom
www.globaledgesoft.com

Uninitialized Data Segment

Wireless

variables.
Data in the BSS segment are initialized to
zero.
Lifetime of uninitialized data is the
complete execution time of the program.

Embedded

It is also called as BSS.


It contains uninitialized static and global

Telecom

Static int a;
Int a;
www.globaledgesoft.com

Heap

Wireless
Telecom

www.globaledgesoft.com

Embedded

Dynamic memory allocation takes place at


the heap segment.
malloc(), calloc(), realloc() can be used to
perform dynamic memory allocation.
Its address space grows from lower to
higher.
The Heap area is shared by all shared
libraries an dynamically loaded modules in a
process.

Stack
Embedded
Wireless
Telecom

All local variables stored under stack


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

References

Wireless

http://see-programming.blogspot.in/2013/10/memory-layoutof-c-program.html

Embedded

http://www.geeksforgeeks.org/memory-layout-of-c-program/

Telecom
www.globaledgesoft.com

Embedded

Wireless

Telecom
www.globaledgesoft.com

You might also like