64

C language

Embed Size (px)

Citation preview

Page 1: C language
Page 2: C language

• 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

Page 3: C language
Page 4: C language

• 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

Page 5: C language

#include<stdio.h>

int main()

{

--other statements

}

Page 6: C language

• 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

Page 7: C language

• 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

Page 8: C language

#include<stdio.h>int main(){

printf(“Hello”);return 0;

}

• This program prints Hello on the screen when we execute it

Page 9: C language

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

Page 10: C language

• Single line comment

– // (double slash)

– Termination of comment is by pressing enter key

• Multi line comment

/*….

…….*/

This can span over to multiple lines

Page 11: C language
Page 12: C language

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

Page 13: C language

• and: & • or: | • xor: ^ • not: ~ • left shift: << • right shift: >>• Useful for bit-field manipulations

#define MASK 0x040if (a & MASK) { … } /* Check bits */c |= MASK; /* Set bits */c &= ~MASK; /* Clear bits */d = (a & MASK) >> 4; /* Select field */

Page 14: C language

• Syntax:condition ? result1 : result2

If the condition is true, result1 is returned else result2 is returned.

• 10==5 ? 11: 1210!=5 ? 4 : 312>8 ? a : b

Page 15: C language
Page 16: C language

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

Page 17: C language
Page 18: C language

• 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

Page 19: C language

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

Page 20: C language

• char ch;• int i;• i = ‘a’; /* i is now 97 */• ch = 65; /* ch is now ‘A’ */• ch = ch + 1; /* ch is now ‘B’ */• ch++; /* ch is now ‘C’ */

• if(‘a’ <= ch && ch <= ‘z’)

• for(ch = ‘A’; ch <= ‘Z’; ch++)

Page 21: C language
Page 22: C language

• 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”);

}

Page 23: C language

• 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)

Page 24: C language

if (condition)

{

stmt 1; //Executes if Condition is true

}

else

{

stmt 2; //Executes if condition is false

}

Page 25: C language

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;

}

Page 26: C language

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

Page 27: C language
Page 28: C language

•When the continue statement is executedinside a loop-statement, the program will skip over the remainder of the loop-body to the end of the loop.

•Syntax

Continue;

Page 29: C language
Page 30: C language
Page 31: C language

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

Page 32: C language
Page 33: C language

• 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 ];

Page 34: C language

• Initializersint 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 itint n[ ] = { 1, 2, 3, 4, 5 };

– 5 initializers, therefore 5 element array

Page 35: C language

• Initialization

– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };

– Initializers grouped by row in braces

– If not enough, unspecified elements set to zeroint b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

• Referencing elements

– Specify row, then columnprintf( "%d", b[ 0 ][ 1 ] );

1 2

3 4

1 0

3 4

Page 36: C language

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

Page 37: C language
Page 38: C language
Page 39: C language

• 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" A \0gnirtS

Page 40: C language

• 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

Page 41: C language

• Allocate an array of a size large enough to hold the string (plus 1 extra value for the delimiter)

• Examples (with initialization):char str1[6] = “Hello”;

char str2[] = “Hello”;

char *str3 = “Hello”;

char str4[6] = {‘H’,’e’,’l’,’l’,’o’,’\0’};

Page 42: C language

• 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

Page 43: C language
Page 44: C language

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

Page 45: C language

• 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:

Page 46: C language
Page 47: C language
Page 48: C language

• 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

Page 49: C language

• Function definition formatreturn-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

Page 50: C language

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

Page 51: C language

• 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

Page 52: C language

• 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

Page 53: C language

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

Page 54: C language
Page 55: C language

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

Page 56: C language

• 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 structuresstruct <<structname>>{

members;}element;We can access element.members;

Page 57: C language

•Compound data:

•A date is

– an int month and

– an int day and

– an int year

Page 58: C language

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

Page 59: C language

• typedef struct student

• {

• int id;

• Char name[10];

• }s;

• Now I can put

• s s1,s2;

Page 60: C language

• A union value doesn’t “know” which case it contains

•Choices:

•An element is

– an int i or

– a char c

union AnElt {

int i;

char c;

} elt1, elt2;

elt1.i = 4;

elt2.c = ’a’;

elt2.i = 0xDEADBEEF;

if (elt1 currently has a char) …

Page 61: C language
Page 62: C language

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”

Page 63: C language

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

Page 64: C language