Ahmed Assem
FORMAT OF A C PROGRAM
/* comment */
#include <Myfile.h>
<global variable declaration>
main()
{
<local variable declaration>
<C statements>
COMMENT
INCLUDE DIRECTIVE
Is the preprocessing
preprocessor.
directive
to
the
INCLUDE DIRECTIVE
Example:
#include<stdio.h>
DATA TYPES
real
Data Types :
Data Type
Size
Range
char
1 byte
-127 to 127
int
2 bytes
-32767 to 32767
float
4 bytes
double
8 bytes
-1.7E-308 to 1.7
E+308
Data Type
Size
Range
signed
int
2 bytes
-32768 to 32767
unsigned
int
2 bytes
0 to 65536
long
int
4 bytes
short
int
2 bytes
-32768 to 32767
VARIABLES DEFINED
that
can
store
2)
3)
4)
5)
6)
7)
KEYWORDS
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
VARIABLE DECLARATION
Syntax:
type variable_list;
Where:
type
variable_list
VARIABLE DECLARATION
Examples:
char name;
int x, y,z;
float number;
VARIABLE INITIALIZATION
Syntax:
type variable_name = value;
Example:
int count = 100;
float grade = 3.75;
char status = S;
Casting
You can force an expression to be of a specific
type by using a cast. The general form of a cast is
(type) expression
where type is a valid data type.
i.e.
int i;
for(i=l; i<=100; ++i)
printf(''%d / 2 is: %f\n", i, (float) i /2);
VARIABLE DECLARATION
Global Variables
Variables that are declared outside a
function. They are known throughout the entire
program.
Local Variables
Variables that are declared inside a function.
They can only be referenced inside that function.
They are also called automatic variables.
Global Variables
#include <stdio.h>
int a,b,c, x,y,z;
main()
{
}
function()
{
}
Local Variables
#include <stdio.h>
main()
{
int a,b,c;
}
function()
{
int x,y,z;
}
MAIN()
Syntax 1:
printf (argument);
Examples:
a=100;
printf (%d, a);
printf (The value is %d, a);
Data Type
character
integer
float/double
Notes:
1. Control string code and argument list should agree in type.
2. They should have a one-to-one correspondence.
Output:
x = 10 and y = 25
z = 123.1234
z = 123.12
PUTCHAR Statement :
putchar(char mychar);
It is used to print a single character or the ASCII
code of a certain integer,
i.e.
putchar (A) ;
Output is A
putchar (65);
Output is A
The format control string indicates the type of data that should
be input by the user.
format control string
Data Type
%c
%d
%f
%lf
character
integer
float
double
GETCHAR STATEMENT
getchar();
Last statement that will be placed before the
closing brace }
Used to input a single character from the
keyboard without echoing the character on the
monitor.
Causes delay in displaying the output once the
program is executed
Syntax:
variable_to_hold_value = expession;
Example:
CS SHORTHAND
x = x + 5;
x+=5;
x = x - 7;
x-=7;
x = x * 12;
x*=12;
x = x / y;
x/=y;
/* Addition Program */
#include < stdio.h >
main( )
{
int integer1, integer2, sum;
printf ( Enter first integer : );
scanf ( %d, &integer1 );
printf ( Enter second integer: );
scanf ( %d, &integer2 );
sum = integer1 + integer2;
printf ( Sum is %d \n, sum );
system(PAUSE);
}
OPERATORS
ARITHMETIC OPERATORS
used
to
perform
Addition
Subtraction
Multiplication
Division
Modulus Division (MOD)
Decrement
Increment
ARITHMETIC OPERATORS
B. Logical Operators
!
Not
&&
And
||
Or
P && Q
P || Q
!P
0 0
0 1
1 1
1 0
BITWISE OPERATORS
BITWISE OPERATORS
&
|
^
~
>>
<<
And
Or
Exclusive Or (XOR)
Ones Complement
Shift Right
Shift Left
BITWISE OPERATORS
1) & (and). Any bit of the operand is 0, the outcome is set to 0.
2) | (or). Any bit on the operand is 1, the outcome is 1
3) ^ (XOR). If exactly one of the operator is 1, the outcome is
one.
4) ~ (Ones complement). Reverse the state of each bit in the
specified variable. That is, all 1s are set to 0, and all 0s are
set to 1.
5) >> (Shift Right). Move all bits in a variable to the right.
6) << (Shift Left). Move all bits in a variable to the left.
BITWISE OPERATORS
1) & (and). Any of the operand is 0, the outcome is set to 0.
E.G 0101 & 0011 = 0001
2) | (or). Any bit on the operand is 1, the outcome is 1
E.G 0101 | 0011 = 0111
3) ^ (XOR). If exactly one of the operator is 1, the outcome is
one.
E.G 0101 & 0011 = 0110
4) ~ (Ones complement). Reverse the state of each bit in the
specified variable. That is, all 1s are set to 0, and all 0s are
set to 1.
E.G ~ 0011 = 1100
5) >> n (Shift Right). Move all bits in a variable n bits to the
right.
E.G ( 10011001 >> 2) = (00100110)
6) << n (Shift Left). Move all bits in a variable n bits to the left.
E.G (00100110 << 2) = (10011000)
Note : shift right means division of the variable by 2^n
The ? : Operator
Exp1 ? Exp2: Exp3;
It is the same as
if (Exp1)
Exp2;
else
Exp3;
i.e.
x = 10;
y = x>9 ? 100 : 200;
Then y will take the value 100
Flow of Control
Operator
Precedence
Meaning
>
greater than
>=
<
<=
2
2
2
==
equal
!=
not equal
Conditional if statements
if (condition1)
{
stmt 1;
else if (condition2)
{
stmt 2;
else
{
stmt 3;
false
}
For loops
While loop
while(condition)
{
statements;
}
Eg:
a=10;
while(a != 0)
{
printf(%d,a);
a--;
}
Output: 10 9 8 7 6 5 4 3 2 1
Do While loop
do
{
set of statements
}while(condition);
Eg:
i=10;
do
{
printf(%d,i);
i--;
}while(i!=0)
Output:
10 9 8 7 6 5 4 3 2 1
Switch Case
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;
}
i.e.
int main (void)
{
int t;
for(t=0; t < 100; t++)
{
printf(''%d ", t);
if(t == 10) break;
}
return( 0 );
}
EXPRESSIONS
Highest
Lowest
Functions
Functions are the building blocks of C
The general form of a function is
Functions
A function can be without parameters, in which
case the parameter list is empty.
An empty parameter list can be explicitly
specified as such by placing the keyword void
inside the parentheses.
Example :
Functions
#include <stdio.h>
int sqr(int x); /* prototype */
int main(void)
{
int t=10;
printf("%d %d", sqr(t), t);
return 0;
}
int sqr(int x)
{
x = x*x;
return(x);
Arrays
An array is a collection of variables of the same
type that are referred to through a common
name.
A specific element in an array is accessed by an
index.
Single-Dimension Arrays
The general form for declaring a singledimension array is
type var_name[size];
double balance[100];
An element is accessed by indexing the array
name. This is done by placing the index of the
element within square brackets after the name of
the array. For example,
balance[3] = 12.23;
The highest index here is 99 and the lowest is 0
Single-Dimension Arrays
#include <stdio.h>
int main(void)
{
int x[100]; /* this declares a 100-integer array */
int t;
/* load x with values 0 through 99 */
for(t=0; t<100; x[t] = t , t++);
/* display contents of x */
for(t=0; t<100; ++t) printf(''%d ", x[t]);
return 0;
Single-Dimension Arrays
Strings
The most common use for the one-dimensional
array is as a character string.
In C, a string is a null-terminated character
array
i.e.
char str [11] ={A,H,M,E,D,A,S,S,E,M,\0};
Or
Char str[11] = AHMEDASSEM
Strings
gets(); reads a string from the user
puts(str) ; writes a string on the screen
strcpy(s1, s2) Copies s2 into s1
strcat(s1, s2) Concatenates s2 onto the end of s1
strlen(s1) Returns the length of s1
strcmp(s1,s2)
Returns 0 if s1 and s2 are the same; less than 0 if
s1<s2; greater than 0 if s1>s2
strchr(s1, ch) Returns a pointer to the first
occurrence of ch in s1
strstr(s1, s2) Returns a pointer to the first
occurrence of s2 in s1
Two-Dimensional Arrays
A two -dimensional array is, essentially, an array
of one-dimensional arrays
It is declared as follows :
Two-Dimensional Arrays
Structures
A structure is a collection of variables referenced
under one name, providing a convenient means of
keeping related information together
It is declared as follows :
struct addr
{
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
};
Structures
struct addr {
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
addr_info.zip = 12345;
gets(addr_info.name)
Structure Assignments
Arrays of Structures
To declare an array of structures, you must first
define a structure and then declare an array
variable of that type.
Example :
printf("%lu", addr_list[2].zip);
Unions
A union is a memory location that is shared by
two or more different types of variables.
Declaring a union is similar to declaring a
structure. Its general form is
union tag {
type member-name;
type member-name;
type member-name;
} union-variables;
Example :
union u_type {
int i;
char ch;
};
Bit-Fields
A bit-field, allows you to access a single bit. Bitfields can be useful for a number of reasons, such
as:
If storage is limited, you can store several Boolean
(true/false) variables in one byte.
Certain devices transmit status information encoded
into one or more bits within a byte.
Certain encryption routines need to access the bits
within a byte.
Bit-Fields
Enumerations
An enumeration is a set of named integer
constants.
Enumerations are common in everyday life. For
example, an enumeration of the coins used in the
United States is
Enumerations
Example
enum coin { penny, nickel, dime, quarter=100,
half_dollar, dollar} money ;
char name[][12]={
"penny",
"nickel",
"dime",
"quarter",
"half_dollar",
"dollar"
};
printf("%s", name[money]);
Enumerations
Example
switch(money) {
case penny: printf("penny");
break;
case nickel: printf("nickel");
break;
case dime: printf("dime");
break;
case quarter: printf("quarter");
break;
case half_dollar: printf(''half_dollar");
break;
case dollar: printf("dollar");
}
Pointers
ADDR1
ADDR2
ADDR3
ADDR4
ADDR5
ADDR6
Contents1
*
*
*
ADDR11
Contents11
*
*
ADDR16
Contents16
Pointers
Pointer Operations in C
Creation
& variable
Dereference
* pointer
Indirect assignment
* pointer = val
Assignment
pointer = ptr
Using Pointers
int i1;
int i2;
int *ptr1;
int *ptr2;
0x1014
0x1010
ptr2:
i1 = 1;
i2 = 2;
0x100C
0x1008
ptr1:
ptr1 = &i1;
ptr2 = ptr1;
0x1004
i2:
2
3
0x1000
i1:
3
1
*ptr1 = 3;
i2 = *ptr2;
0x1000
0x1000
Pointer Arithmetic
pointer + number
pointer number
E.g., pointer + 1
char
char
char
*p;
a;
b;
p = &a;
p += 1;
int
int
int
Adds 1*sizeof(char) to
the memory address
*p;
a;
b;
p = &a;
p += 1;
Adds 1*sizeof(int) to
the memory address
Generic Pointers
Pass-by-Reference
void
set_x_and_y(int *x,
int *y)
{
*x = 1001;
*y = 1002;
}
void
f(void)
{
int a = 1;
int b = 2;
set_x_and_y(&a,&b);
}
1001
1
1002
2
x
y
Pass-by-Reference
#include <stdio.h>
void swap ( int *a, int *b ) ;
int main ( )
{
int a = 5, b = 6;
printf("a=%d b=%d\n",a,b) ;
swap (&a, &b) ;
printf("a=%d b=%d\n",a,b) ;
return 0 ;
}
Dirty secret:
Array pointer to the initial (0th)
array element
a[i]
*(a+i)
Passing arrays:
Really int *array
Must explicitly
pass the size
int
foo(int array[],
unsigned int size)
{
array[size - 1]
}
int
main(void)
{
int a[10], b[5];
foo(a, 10) foo(b, 5)
}
printf(%d\n, sizeof(array));
}
int
main(void)
{
int a[10], b[5];
foo(a, 10) foo(b, 5)
printf(%d\n, sizeof(a));
}
40
int
int
i;
array[10];
int *p;
int array[10];
for (p = array; p < &array[10]; p++)
{
*p = ;
}
Data Structure
What is a stack?
AHMED1
Top
1
D
E
M
H
A
Pop side
Push side
Data Link
NULL
Head
Data Link
NULL
Head
Data Link
Head
Data Link
NULL
Data Link
Data Link
Head
Data Link
Data Link
Data Link
NULL
Head
Head
Data Link
NULL
Data Link
Data Link
Stack applications
Rule: { ok string } is OK
Rule: ( ok string ) is OK
Use a stack
Place left braces and parentheses on stack
When a right brace / paren is read, pop the
left off stack
If none there, report an error (no match)
Stack applications
3)
read (data)
loop (data not EOF and stack not full)
1) push (data)
2) read (data)
Loop (while stack notEmpty)
1) pop (data)
2) print (data)
Addition side
Extraction Side
Data Link
Head
Data Link
ptr
Data Link
Data Link
Head
Data Link
ptr
Data Link
Data Link
Data Link
NULL
Data Link
ptr
NULL
Head
NULL
Data Link
NULL
Data Link
Head
Data Link
Data Link
ptr
Data Link
Head
Data Link
Data Link
NULL
Data Link
ptr
Data Link
NULL
Data Link
NULL
ptr
Head
Head
Data Link
NULL
Assignment
1)
Preprocessor
Directives
Macro definitions
#define
To define preprocessor macros we can use #define.
Its format is:
#define identifier replacement
#undef
This commands undefined a macro. A macro must
be undefined before being redefined to a different
value
Conditional inclusions
#ifdef
Allows a section of a program to be compiled only if the macro
that is specified as the parameter has been defined, no matter
which its value is
#endif
End the if section
#ifndef
Serves for the exact opposite: the code between #ifndef and
#endif directives is only compiled if the specified identifier has
not been previously defined.
#if, #else and #elif
Serve to specify some condition to be met in order for the
portion of code they surround to be compiled. The condition
that follows #if or #elif can only evaluate constant expressions,
including macro expressions
Other directives
Error directive (#error)
This directive aborts the compilation process when it is found,
generating a compilation the error that can be specified as its
parameter:
Source file inclusion (#include)
This directive includes a file into code.
It has two possible forms:
#include <file> or #include ``file''
<file> tells the compiler to look where system include files are
held.
``file'' looks for a file in the current directory (where program
was run from)
Included files usually contain C prototypes and declarations
from header files and not (algorithmic) C code #ifndef
Serves for the exact opposite: the code between #ifndef and #endif
directives is only compiled if the specified identifier has not been
previously defined.
Other directives
Pragma directive (#pragma)
This directive is used to specify diverse options to the compiler. These options
are specific for the platform and the compiler you use. Consult the manual or
the reference of your compiler for more information on the possible
parameters that you can define with #pragma.
Some Embedded
Systems Concepts
functions:
will return control to caller only after
finishing its task
Asynchronous functions:
will just start its task and return control to
caller, while
its task is continue in the
background
Recursive Functions
Recursive function is function that call itself.
Software Timeout
Timeout mechanism is used to release the CPU while waiting for an
event when this event does not triggered within the specified timeout
period.
To implement Timeout:
Timeout period is determined from the nature of the event
Timeout can be implemented by hardware timer or by software
depending on available resources and needed accuracy
Actions to be performed when timeout expired
Critical Section
A critical section of code, also called a critical region, is code
that once starts executing, it must not be interrupted.
To ensure this, interrupts are typically disabled before the
critical code is executed and enabled when the critical code is
finished.
Byte Ordering
Big-endian:
Store most significant byte in low address and least significant byte in
high address (Freescale)
Little-endian:
Store least significant byte in low address and most significant
byte in high address (Intel)
Bi-endian:
Can be configured to efficiently handle both big and little endian
(PowerPC).
Byte Ordering
References :