You are on page 1of 64

HAND IN HAND WITH

C LANGUAGE

FEATURES
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

HISTORY
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

PROGRAMME
STRUCTURE
#include<stdio.h>
int main()
{
--other statements
}

HEADER FILES
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

MAIN FUNCTION
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

FIRST PROGRAMME
#include<stdio.h>
int main()
{
printf(Hello);
return 0;
}
This program prints Hello on the
screen when we execute it

RUNNING A PROGRAMME
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.

COMMENT IN C
Single line comment
// (double slash)
Termination of comment is by pressing
enter key

Multi line comment


/*.
.*/
This can span over to multiple lines

KEY WORDS

C EXPRESSION CLASSES

arithmetic: + * / %
comparison: == != < <= > >=
bitwise logical: & | ^ ~
shifting: << >>
lazy logical: && || !
conditional: ? :
assignment: = += -=
increment/decrement: ++ -sequencing: ,
pointer: * -> & []

BITWISE OPERATORS

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 */

CONDITIONAL OPERATOR
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

DATA
TYPES

DATA TYPE
A data type defines a collection of
data objects and a set of
predefined operations on those
objects.

DATA TYPE

VARIABLE
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

VARIABLE NAMING
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.

CHARACTER TYPE

char ch;
int i;
i = a;
ch = 65;
ch = ch + 1;
ch++;

/* i is now 97 */
/* ch is now A */
/* ch is now B */
/* ch is now C */

if(a <= ch && ch <= z)


for(ch = A; ch <= Z; ch++)

CONTROL

FOR LOOP
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);
}

DO WHILE LOOP
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)

CONDITIONAL | IF ELSE
if (condition)
{
stmt 1;
//Executes if Condition is true
}
else
{
stmt 2;
//Executes if condition is false
}

CONDITIONAL | SWITCH
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;
}

BREAK
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;

BREAK

CONTINUE
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;

CONTINUE

ARRAY

ARRAY
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 ]

ARRAY

DECLARING ARRAY
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 ];

USING ARRAY
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

MULTI DIMENTIONAL
ARRAY
Initialization
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
1
2
Initializers grouped by row in braces
3
4
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
3

0
4

MULTI DIMENTIONAL
ARRAY
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

STRING

STRING
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"

\0

STRING
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

STRING VARIABLE
Allocate an array of a size large enough
to hold the string (plus 1 extra value for
the delimiter)
Examples (with initialization):
char
char
char
char

str1[6] = Hello;
str2[] = Hello;
*str3 = Hello;
str4[6] = {H,e,l,l,o,\0};

STRING FUNCTIONS
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

POINTER

POINTER
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;

USING POINTER
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:

USING POINTER

FUNCTIONS

FUNCTIONS
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

FUNCTIONS DEFINITION
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

FUNCTIONS DEFINITION

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;

FUNCTIONS CALLING
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
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

RECURSIVE FUNCTIONS
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;

STRUCTURE
UNION
TYPEDEF

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

STRUCTURE
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;

STRUCTURE
Compound data:
A date is
an int month and
an int day and
an int year

TYPEDEF
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

typedef struct student


{
int id;
Char name[10];
}s;

Now I can put


s s1,s2;

UNION
A union value doesnt know which
case it contains union AnElt {
int
i;
Choices:
char c;
} elt1, elt2;

An element is
an int i or
a char c

elt1.i = 4;
elt2.c = a;
elt2.i = 0xDEADBEEF;
if (elt1 currently has a char)

MACRO

MACRO PREPROCESSOR
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

MACRO PREPROCESSOR
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