Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

C Basics

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C Basics

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

C programming language Basics

(Part1)
Data types in C
Type Bits Bytes
char 8 1
unsigned char 8 1
short 16 2
Unsigned short 16 2
int 32/16 4/2
unsigned int 32/16 4/2
long 32 4
unsigned long 32 4
Long long 64 8
float 32 4
double 64 8

Casting in C
Implicit Casting Explicit Casting
Casting doesn’t require a casting operator, normally Casting that require a casting
used when converting data from smaller integral types operator.
to larger. Ex:
int x = 10, y=2;
float sum;
sum= (float) x+y;

C operators
1- Arithmetic operators (by the order of precedence)
Operator Operation Order of precedence
() parentheses Evaluated first
* Multiplication
Evaluated second, they are evaluated from left to
/ Division
right if they are several.
% Remainder
+ Addition Evaluated last. they are evaluated from left to right
- subtraction if they are several.
2- increment and Decrement Operators
Pre-fix Post-fix
Increment a by 1 then use the Use the current value of a then
++a a++
new value increment a by 1
Decrement a by 1 then use the Use the current value of a then
--a a--
new value decrement a by 1

1
3- Relational operators
== x == y x is equal y
!= x != y x is not equal y
> x>y x is greater than y
< x< y x is less than y
>= x >= y x is greater than or equal y
<= x<=y x is less than or equal y
4- Logical Operators
&& x && y Logical AND operator
|| x || y Logical OR operator
! !x Logical NOT operator
5- Bitwise operator
& AND
| OR
^ XOR
~ One’s Complement
<< Shift left
>> Shift right
6-Assignment operator
= Simple assignment
+= Add then assign
-= Subtract then assign
*= Multiply then assign
/= Divide then assign
%= Modulus then assign
<<= Left shift then assign
>>= Right shift then assign
&= AND then assign
|= OR then assign
^= XOR then assign

Decision Making in C
if-Statement
if (control expression) {
 Program code is executed or skipped.
Program statement1;
 If the control statement is true, the body is
Program statement2;
executed. If its false, the body is skipped.

}
If-else statement
if (control expression) {
 Used to Decide between two actions.
Program statement1;
 If exp. is true statement1, is executed and
}
statement2 is skipped.
else {
 If exp. is False statement1, is skipped and
Program statement2;
statement2 is executed.
}

2
If else if else statement
if (control expression1) {
Program statement1;
}
 Allow you to check for multiple test expressions
else if (control expression2) {
and execute different codes for more than two
Program statement2;
conditions.
else {
Program statement3;
}
Conditional operator
 If the condition is true (non-zero),
expression 1 is executed and if false(zero)
Condition? Expression1: expression2;
expression2 is executed

Switch Statement
switch (integer expression) {
case constant1:
 A way of writing a program which employs an if-else
statement1;
statement ladder (nested if), it jumps on the case
break;
which match with the integer expression.
case constant2;
 Break should be included to exit the case; no break
statement2;
makes all the statement executed until we reach
break;
break keyword.

 Default can be put anywhere not only at the end of
default:
switch statement.
statement;
}

Loops in C
WHILE loop
Steps:
1. Control expression is evaluated.
while (control expression) {
2. If false, loop is skipped.
Statement1;
3. If true, loop body is executed.
Statement2;
4. Then we return to the control expression.
.....
It’s the programmer responsibility for initialization and
}
increment at some point in the body of loop otherwise it
will be infinite loop.
FOR loop
Control expression is separated by ‘;’ not comma.
for (initialization expression; test
Steps:
exp.; increment exp.) {
1. Initialization expression is evaluated.
Statement1;
2. The test expression evaluated, if it’s true,
Statement2;
body of loop is executed. If false we exit the
}
loop.

3
3. Assume it’s true, execute the body then
evaluate the incremental expression and
return to step 2.
DO..WHILE loop
 This loop is ended by semicolon (;).
 It’s made to do the statement before checking the
do {
condition.
Statement1;
 Ex: we check the user entered the right data by scanf.
Statement2;
 The do-while body loop is executed at least one time.
} while (condition);
 If condition is true we get back to the body of the loop.

Break and Continue Keywords


break continue
When executed in a while, for , do..while
When executed in a while, for , do..while
statement, skips the remaining statements in
or switch statement, cause an immediate
the body of that control statement and
exit from that statement.
perform the next iteration of the loop

4
C programming language Basics
(Part2)

Functions In C
A function in C is a small Sub program that perform a particular task.
Every C program has at least one function main()
In order to use your own functions, the programmer must do the following:
1. Define the function.
2. Declare the function (prototype).
3. Use the function in the main code.
Syntax:
Return_type function name (data_type variable name list) {
/*Function body*/
Local declaration;
Function statements;
}
All variables defined in the function definitions are local variables they are known only in
the function in which they are defined.
Local Variables are pushed to the stack at the beginning of the function and popped from
the stack at the end of the function.
The purpose of function declaration (prototypes) is to know the functions name , number
of inputs , data type of inputs and the return type.
Function declaration is required in two cases:
1. when you define a function below another function that call this function in the
same source file.
2. When you define a function in one source file and you call that function in another
file.
Definition = Declaration + Space Reservation
Void Functions
Void means No type , or No value or No parameters
In Functions Void can be used to:
1. The function does not return value.
2. Function does not accept parameters.
Function Arguments and Function parameters
In programming, the terms "function arguments" and "function parameters" are often
used interchangeably, but they have slightly different meanings.
Function Arguments Function Parameters
Arguments are the actual values passed to a Parameters are placeholders or variables
function when it is called. defined in the function declaration or
definition.
Arguments are the concrete values that are They represent the values that a function
supplied as input to a function. expects to receive when it is called.
Data can be passed to functions as an argument in two ways:

1
1. Pass by value.
2. Pass by Reference.

Pass by value Pass by Reference


Method that copy the actual value of an Method that copies the address of an
argument into formal parameter of the argument into the formal parameter.
function.
Any changes made to the parameter inside Any changes that made to parameter
the function have no effect on the affect the arguments.
argument.
Recursive function
Function that call itself.
Not recommended in Embedded software due to:
1. High stack consumption.
2. The execution time needed for the allocation and de-allocation, and for the
storage of those parameters and local variables has high cost.
3. These type of function is hard to be tested and hard to read.
4. You need to make precautions to ensure that recursive routine will be terminated
otherwise stack overflow will occur.

Arrays and strings in C


Arrays
Is a data structure which can store a fixed size sequential collection of elements/data of
the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
To declare a single dimensional array:
Data_type Array_name [ array_size ];
All arrays have 0 as the index of their first element which is also called base index. And
last index of an array will be total size of the array minus 1. (n-1) where n is total size of
the array.
Arrays are initialized when declared otherwise you can put data in it using for loop.
for (i=0; i<n; i++) {}
N is number of elements in the array.
If there are fewer initializers than elements in the array, the remaining elements are
initialized to ZERO.
Array name is a constant pointer holds the first element address.
Array size can’t be input from the user or variable, so it can’t be changed in the runtime.
So make sure to use all memory allocated.
Array size= data type(in bytes) * number of elements(n)
Passing array elements to functions can be by reference (&array[i]) or by value (array[i])
Passing whole array to function is ALWAYS by reference (just write the array name is
possible because Array name is address of first address and other elements are
contiguous). + we must pass array size.
Unlike char arrays that contain strings we pass only the name of the string.(due to the
special terminator which indicate the end of the string.)

2
To declare a Multi-dimensional array:
Data_type Array_name [ row ][ col ];
We can access multi-dimensional array by using 2 nested for loops:
for (i=0; i<row; i++) {
for (j=0; j<col; j++) {}
}
Passing a Multi-dimensional array is by its name only.
We must write COL (number of element in each array) when we initialize or declare the
multi-dimensional Array.
Strings
Strings are considered as 1D array of characters. Terminated by the NULL character ( \0 )
Initialize be like:
char str[6]={‘h’,’e’,’l’,’l’,’o’,’\0’};
Char str[6] =” hello”;
Char str[]=”hello”;
You must specify the maximum number of characters you will ever need to store in an
array. As it will be fixed at run time of the program (static allocation).
You should count the end of string character to calculate the size of a string.
When you use printf to print a string use %s to print all string until it find \0
To take string from user use ( gets(str_name); ) function.
String functions: you should include library “string.h”
Function Usage
Strlen(s1) Calculate the length of string.
Strcpy(s2,s1) Copies a string to another string.(in s2)
Strcat(s3,s1) Concatenates two strings (in the first argument s3).
Compare two strings. (compare by the character value)
 s1>s2 = 0
Strcmp(s1,s2)
 s1<s2= -ve
 s1=s2= +ve
Strlwr() Converts string to lowercase.
Strupr() Converts string to uppercase.
It can be array of strings
Ex: char str[2][20]={“embedded”,”systems”};
You can access it just like arrays.

Pointers in C
Variables whose values are memory location
A pointer contain an address of a variable that contain a specific value.
Address operator (&) is a unary operator that returns the address of its operand.
int x=2;
int *xPtr= &x;
The dereferencing operator or indirection operator (*) is a unary operator that returns the
value of the object to which its operand (pointer) points.
*xPtr=10; //x=10
Pointers just like variables must be defined before we use it.
int *xPtr;

3
Direct way to define X=5; Indirect way to define a int x=2;
a variable variable int *xPtr= &x;
Pointers can be defined to point to objects of ANY TYPE
Pointers can be initialized to NULL, 0 or an Address
Size of pointer is the address path of the architecture that is used.
Arrays and pointer are intimately related in C as the array name can be thought of as a
constant pointer. (SO WE CAN’T MODIFY ADDRESS OF ARRAY NAME WITH POINTER
ARITHMETIC)
Ex:
arr[5];
arrPtr=b; or arrPtr= &b; or arrPtr=&b[0];
/*all are the same*/
Array element arr[3] can be accessed:
arr[3]=5;
*(arrPtr+3) = 5;
/*Or by using array name*/
arr[3]=5;
*(arr+3)=5;
Pointer arithmetic
There are set of arithmetic operations may be performed on pointers, pointers can be:
1. Incremented ++ .
2. Decremented - - .
3. Added to a pointer (+or +=).
4. Subtracted from a pointer (- or -=).
5. One pointer subtracted from another pointer.
Pointer arithmetic follow this rule:
Ex: int*ptr;
ptr+=2;
Ptr=Ptr+(data type of the pointer *N) // N=2
Const Keyword
Non const pointer Const pointer to Const pointer to const
Const variable
to const data. non const data data
Inform the compiler Can be modified Always point to the Pointer always point to
that value of a to point any data same memory the same memory
particular var. item but the data location and the location and the data at
should not be to which it points data at that that memory location
modified cannot be location can be cannot be modified.
Const x = 10; // must modified. modified. Const int * const ptr=&x;
be initialized Const int *ptr; Const pointers
Int const x = 10; must be initialized
// is the same when defined.
meaning. Int * const ptr=&x;

4
Pointer Types
1- Void pointer
It’s a general purpose pointer variable it can be assigned to any data type variable without
casting operator BUT we can’t dereference the void pointer (Segmentation fault) to
dereference void pointer you need to use EXPLICIT CASTING.
2- Dangling pointer
Is a pointer that points to deleted object or de-allocated object, if you try to de-reference
that pointer, this will cause a segmentation fault.
3- Wild pointer
A pointer that is not initialized, the uninitialized pointers behavior it totally undefined
Or
Any pointer in programming languages that are not initialized either by compiler or
programmer begins as a wild pointer.
int * ptr;
4- NULL pointer
We use Null pointers as initial value for the uninitialized pointers.it prevents the pointer to
become a dangling pointer and ensure the programmer that pointer is not pointing
anywhere
int* ptr= NULL;
5- Pointer to char
Used when we don’t want to say how many characters in the string may hold.
We declare a pointer of type char to hold address of character variable
Char*a=”Hello”;
Pointer a stores the base address. And all the string is stored in a shared READ ONLY
location. You can’t change any member of (Hello) string.
Unlike the array name a is a non-constant pointer so we can change it. a= “World”;
6- Pointer to Pointer
When we define a pointer to pointer, the first pointer contain the address of the second
pointer, which points to the location that contains the actual value.
Int**ptr;
One of the important usage of pointer to pointer in C language is when we need to pass a
pointer to pointer by address.
7- Array of pointers
It Is an array containing pointers.
int *ptr[3];
this declare ptr as an array of 3 integers pointers, so each element holds a pointer to int.
value
A common use of an array of pointers is to form an array of strings refered to simply as a
string array
Char *ptr[3]={“hello”,”Embedded”,”system”};
8- Pointer to Array

Its usage to declare a pointer to MULTI-dimensional array.


int arr2D[][5]={…..};
int (*ptr2D)[5]=arr2D;

5
9- Pointer to function
A function pointer is a variable that stores the address if a function that can later be called
through that function pointer.
A function name is the start address of the function code in the memory.
Pointers to function can be passed to functions, returned from functions, stored in arrays
and assigned to other function pointers.
Definition:
Return_value(*Ptr_name) (Argument_type);
Initialization:
Ptr_name=func_name;
Calling:
Ptr_name(argument_name); OR (*Ptr_name)(argument_name);

You might also like