You are on page 1of 103

C PROGRAMMING

CONTENTS
 C DATA TYPES  OPERATORS  ARRAYS  PASSING ARRAYS TO FUNCTIONS  STRUCTURES  POINTERS  MEMORY ALLOCATION  FILE HANDLING  MACROS  UNION  HARDWARE RELATED C-COMMUNICATING THROUGH UART  DATA STRUCTURES
1
Advance C Concepts

Introduction to C
 C is

middle level language developed AT&T bell laboratory. developed at Cambridge university. It was so big and hard to learn

 CPL- combined programming language was

 BPCL- Basic combined programming language was

developed by Martin Richards of Cambridge university. Too less powerful and too specific
 B was developed by

Ken Thompson. Too specific inheriting the

 Later Dennis Ritchie developed C

properties of B and Bpcl


2
Advance C Concepts

Constants, variables and data types


Constants entity whose value does not change during programming execution Variables entity whose value changes with program execution Data types int, char, float, double, long,

Advance C Concepts

Structure of C Program
 Processor directives  Function declaration and definitions  Any C

program must have a main function which is function can call other library functions

the entry point for all the program


 The main

and user defined functions.

Advance C Concepts

Format control
Signed charater Unsigned character Short signed int Short unsigned int long signed int long unsigned int float double long double
5

%c %c %d %u %ld %lu %f %lf %Lf


Advance C Concepts

Arithmetic Operators
 The binary arithmetic operators are

+, -, *, /, and the modulus operator %. Integer division truncates any fractional part. The expression x % y produces the remainder when x is divided by y, and thus is zero when y divides x exactly.  The *, / and % have same priority which has higher priority that binary operators + and - .  In case of expression containing the equal precedence it gets evaluated from left to right
6
Advance C Concepts

The Relational Operators


 The relational operators are  They all

> >= < <=

have the same precedence. Just below them

in precedence are the equality operators: == !=


 Relational operators have lower precedence than

arithmetic operators, so an expression like i< lim-1 is taken as i < (lim-1), as would be expected.

Advance C Concepts

The Logical Operators


&& | |

logical AND. Returns 1 when both end are same

- logical OR . Returns 1 when both the end are

non- zero.
!

- inverting && or || are evaluated left or

Expressions connected by

to right, and evaluation stops as soon as the truth falsehood of the result is known.
Most C

programs rely on these properties.


8
Advance C Concepts

Unary and Ternary operator


 ++  --

increments the operand value by 1. used after the variable. (eg) x++ used before the variable. (eg) ++x

- decrements the operand value by 1.

 Post fixing  Prefixing  ?: is

called ternary operator Exp1 : Exp2 taken as the alternate way for if condition.
9
Advance C Concepts

 Exp1 ?

 Requires three operators.  Can be

Compound Assignment Operator


Binary operators like

+,* have a corresponding assignment operator of the form op= where op is the one of +,-,*,/,%,&,|,^. Example if i=15  i+=3 changes the value of i to 18.  i-= 3 change the value of i to 12.  i*= 3 change the value of to 45.  I/= 3 change the value to 5 Size of operator returns the number of bytes the operand occupies.
10
Advance C Concepts

Precedence of operation

11

Advance C Concepts

Bitwise operator
   

& - bitwise AND | - bitwise OR ^ - bitwise EXOR This can be applied to any data type.

12

Advance C Concepts

Type Conversion
When an operator has operands of different types, they are converted to a common type according to a small number of rules.

13

Advance C Concepts

Type Casting
Explicit type conversion can be forced in any expression with unary operator is called as cast. The expression is converted to the named type of conversion rules.

14

Advance C Concepts

Control Statements

15

Advance C Concepts

If Condition
Used to specify the conditional execution of a program statements enclosed in braces.

16

Advance C Concepts

If - Else Condition

17

Advance C Concepts

Switch Case
The switch is multi way decision that tests whether an expression matches one of a number of constant integer values.

18

Advance C Concepts

Loop Control
This allows a sequence of program statements to be executed several times, either for specific number of times or until a particular condition is satisfied.  It has three parts loop variables, loop continuation condition, loop body and an exit point.  There are three main loops
 The while loop Do while loop For loop  

Pre- test loop while and for loops Post test loop do while loops
19
Advance C Concepts

While loop
 If

the expression evaluated is a non-zero the body loop is executed. body , it again evaluates the expression and if it is true again the body loop is executed.

 After execution of

20

Advance C Concepts

Do While
In case of Do- while the body is executed once and the expression is evaluated once.  If expression is true the body is executed again.


21

Advance C Concepts

For loop
The most preferred loop is for loop when we have simple initialization and increment.

One or more variable can be initialized and decremented.

22

Advance C Concepts

Loop Interruption
Loop interruption are required when we want to exit from a loop other then by testing the loop termination condition at the top or bottom.  There there are three interruption commands Break Continue Exit Goto is a control directive where the program control is transferred.  C provides the infinitely-abusable goto statement, and labels to branch to. Formally, the goto statement is never necessary, and in practice it is almost always easy to write code without it.

23
Advance C Concepts

Break Statement
The break statement provides and early exit from for,do, while just as switch.

24

Advance C Concepts

Function
 A function is

a self-contained block of program that performs some specific, well-defined task.  Separating a program into multifunction aid in maintenance and enhancement of programs by localizing the effect of changes.  There are two types function Library function User-defined function  Commonly used functions written,compiled,and placed in libraries are called Library function [eg Printf(), scanf()]  User has the freedom to choose the function name, return data type and the arguments.
25
Advance C Concepts

Function declaration and Prototype


 The general form

of a function declaration is

 Where return-type data type of the value returned  Function name name of the function defined  Argument deceleration types and names of the

parameters of the function, separated by commas.  Function declaration is also called as function prototype.  Ex. int func1(int);
26
Advance C Concepts

Function definition
A function definition introduces a new function by declaring the type of the value it returns and its parameters, and specifying the statements that are executed when the function is called.

27

Advance C Concepts

Function Call

28

Advance C Concepts

If the program contains multiple functions, their definitions may appear in any order. Though they must be independent of one another.  The function cannot be embedded with another

29
Advance C Concepts

Return Statement
 Functions which require a

return value should

use the return statement.

On executing the return statement, the value of the expression, which is just after the return keyword, is returned to the calling function.  If the expression is not present, it returns an integer or void depending on the compiler that you use.

30
Advance C Concepts

Function Argument


The function parameters are a means of communication between the calling and the called function. Conditions for function call The list of arguments in the function call and function declaration must be the same. The data type of each of the actual parameter must be the same as that of the formal parameter. The order of the actual parameters must be the same as the order in which the formal parameters are specified.ie

31

Advance C Concepts

Passing Arguments to a Function


 Passing arguments has two

mechanismPassing arguments by value (call by value) Passing arguments by address or pointers (call by reference)  Call by value the contents of the arguments in the calling function are not changed, as the contents of the variable are copied to the formal parameters of the function definition.  Call by reference memory address of the variable is passed to the function definition, so the argument value changes.
32
Advance C Concepts

Recursion
Recursion is a process by which the function can call itself repeatedly, until some specified condition is satisfied .  Direct if the call to the function occurs inside the function itself.  Indirect if a function calls another function and which in turn calls the first one.


33

Advance C Concepts

Storage Glass
The storage class determines the life time of the shortage associated with the variable. There are two types locations store c can store
 

Memory CPU registers There are four storage classes Automatic storage class Static storage class Register storage class External storage class
34
Advance C Concepts

Automatic Variables
A variable is said to automatic if it is allocated storage upon entry to a segment of code, and the storage is reallocated upon exit from the segment. Syntax auto data type variable name;

35

Advance C Concepts

Static Variables
A variable is said to static , if it is allocated storage at the beginning of the program execution and the storage remains allocated until the program execution terminates. Syntax static data type variable name;

36

Advance C Concepts

Register Variables
Variables will be placed in the internal CPU registers, as accessing internal registers take less time than accessing memory. When a variable is is used at many places in a program it is better to declare its storage class as register Syntax register data type variable name;

37

Advance C Concepts

External Variable
If the declared variable is needed in another file, or in the same file but at a point earlier than that at which it has been defined , it must be declared of storage class external. Syntax extern data type variable name;

38

Advance C Concepts

Arrays
An ordered finite collection of data items, each of the same type, is called an array and the individual data items are its elements. Arrays, whose elements are specified by one subscript , are called one dimensional arrays. They are commonly known as vectors. Arrays, whose elements are specified by more than one subscript , are called mulit dimensional arrays. They are commonly known as matrix.

39

Advance C Concepts

Single Dimensional Array

Elements of an array can be assigned a initial value by the following the array the array definition with a list of initializers enclosed braces and separated by commas.

40

Advance C Concepts

Multi Dimensional Array


They are defined the same way as single dimensional arrays, except that a separate pair of of square brackets is required for each subscript (dimension).

41

Advance C Concepts

Initializations of Two Dimensional Array

42

Advance C Concepts

Strings
 A string

is one dimensional array of characters terminated by '\0' character.

String are used to store text information and to perform manipulations on them. example char name[6]; character arrays Char name[] = {'S', 'N' , 'A' , 'D', 'S' }

43

Advance C Concepts

Built-in string functions


The header file string.h provides a useful set of string functions.

44

Advance C Concepts

Pointers
 Pointers enable us

to achieve parameter by passing by reference , deal concisely and effectively either arrays, represent complex data structures and work with dynamically allocated memory.  Pointer variable address of a data item is called pointer to the data item and a variable that holds an address is called a pointer variable. Uses of pointers

Keep track of address of memory location


By changing the address in the pointer type variable you can manipulate data in different memory locations. Allocation of memory can be done dynamically
45
Advance C Concepts

Pointer Declaration
Pointers are also variables and hence, must be defined in program like any other variable.

46

Advance C Concepts

Pointer Initialization
The declaration of the pointer may be accompanied with the initializer. Type * identifier = initializer E.g., float *fp=null; Pointer arithmetic can be performed only for addition and subtraction .

47

Advance C Concepts

Pointer and Functions


A function can take a pointer to any data type, as argument and can return a point to any data type

48

Advance C Concepts

Call By Value
The values of the argument are used to initialize parameters of the called function.

49

Advance C Concepts

Call By Reference
Here the address of the variable are supplied to the calling function and changes to the parameter values in the called function cause changes in the value of the variable in the calling function.

50

Advance C Concepts

Pointer to Functions
A pointer to function can be defined as a the address of the code executed when the function is called. Pointer to function are used in
 Writing memory resident programs  Writing viruses, or vaccines to remove the

viruses

Declaration of pointer to function -

51

Advance C Concepts

Pointer to Functions

52

Advance C Concepts

Pointer and Array Pointer and array


Any operation that can be done by array can also be done with pointers.

53

Advance C Concepts

Array as Function Arguments

54

Advance C Concepts

Array of Pointers
An array of pointer is a collection of address. The address present in the array of pointers can be addressed of isolated variables or addresses of array elements or any otheraddress. Ex char *day[7]; Char * day[7] = {sun,mon,tue,wed,thur, fri,sat};

55

Advance C Concepts

Functions Returning Pointers

56

Advance C Concepts

Pointer and Array


Any operation that can be done by array can also be done with pointers.

57

Advance C Concepts

Array of Pointers
An array of pointer is a collection of address.  The address present in the array of pointers can be addressed of isolated variables or addresses of array elements or any other address.  Ex char *day[7]; Char * day[7] = {sun,mon,tue,wed,thur, fri,sat};


58

Advance C Concepts

Multi dimensional array as array of pointers


 A multidimensional array can be

expressed in terms of an array of pointers rather than as a pointer to a group of contiguous arrays.  A two dimensional array can be defined as as one dimensional array of pointers like - data type -*array[exp1]; rather than data type array [exp1][exp2];
59
Advance C Concepts

Functions returning pointers

60

Advance C Concepts

61

Advance C Concepts

Dynamic memory allocation


C provides a collection of dynamic memory management functions enable storage to be allocated as needed and released when no longer required.  Header files required- malloc.h, alloc.h  Void *malloc(size) to obtain storage for a data item  Void *calloc(nitems,size) storage for more than on data item  Void *realloc(void *block, size) allocates memory for the new size. If the new size is larger than the older one , the original contents are preserved and the remaining space is uninitialized; if smaller the contents are unchanged up to the new size.  free(ptr) clear the memory allocated.

62
Advance C Concepts

Pointer Declaration

63

Advance C Concepts

Structure
Structure is collection of logically related data items grouped together under a single name called structure.

64

Advance C Concepts

Declaration Individual Member of Structure


Individual members of a structure may be any of the common used data types (such as int,float, etc.), pointers, array, or even other structures.  Structure variables 

Structure variable can also be declared as Struct tag variable list ex struct student student1 , student2
65
Advance C Concepts

Accessing structure members


 With the

help of dot operator (.), individual elements of the structure can be accessed and syntax is of the form  Structure variable . Member- name  Ex student1.name

66

Advance C Concepts

67

Advance C Concepts

Arrays of structure
These are commonly used when a large number of similar records are required to be processed together. Ex struct item motor[100] ;

68

Advance C Concepts

Pointers to Structures
The beginning address of a structure can be accessed in the same manner as any other address, through the use of the & operator. The member variables can be accessed by Pointer name -> member variable

69

Advance C Concepts

Structure and Functions


  

A structure type definition may be local to a function or it may be external to any function. Structures may be passed as function arguments and functions may be return structures. Structure as function arguments. There are three methods Passing structure member to function Passing entire structure to function Passing structure pointers to function

70

Advance C Concepts

71

Advance C Concepts

Passing entire structure to a function

72

Advance C Concepts

Structure as Functions Values

73

Advance C Concepts

Passing structure pointers to Functions

74

Advance C Concepts

File Handling
C provides functions to get data from a file stored in disk. These function are classified as  High level file I/O functions also called as standard I/O or stream I/O functions.  Low-level file I/O functions also called as system I/O functions. Unformatted high level disk I/O functions. fopen () function FILE *fp; fp=fopen(file_name, type/mode);
75
Advance C Concepts

76

Advance C Concepts

File Related Functions-general


fclose function fclose(fp); Character I/O in files fgetc(fp); putc(c,fp); String line I/O in files Char *fgets(char *s, int n, FILE *fp); Int fputs(const char *s, FILE *fp); Formatted high level disk I/O functions fprintf(fp, format,s); fscanf(fp, format,s); Disk I/O fread(ptr,size,nitems,fp); fwrite(ptr,size,nitems,fp);
77
Advance C Concepts

File Related Functions-general


Error handling functions Int feof (FILE *fp); Int ferror (FILE *fp); void perror(const char *s); File positioning functions Int fseek (FILE *fp, long offset, int ptrname);

78

Advance C Concepts

C Pre Processor
 It

is a program that process the source text of a C program before the program is passed to the compiler.  It has four major functionsMacro replacement Conditional compilation File inclusion Error generation C Preprocessor offers several features called Preprocessor directives. Each of the preprocessor begin with # symbol. #define directive include directive undef directive #error directive Conditional compilation directives
79
Advance C Concepts

Macro Substitution
 # define macro-name sequence-of-tokens  Macros with arguments

#define AREA (r) (3.14*r*r) Nesting of macros #define SQUARE(x) x*x #define CUBE(x) (SQUARE(x) * x) We can use one macro in the definition of another macro.  Undefining a Macro # undef identifier

80

Advance C Concepts

File Inclusion
 This preprocessor directive causes one

file to be included in another. This feature is used in two cases If we have a large program, it is good programming practice to keep different sections in separate file. These file are included at the beginning of main program file. Many a times we need some functions or some macro definitions almost in all programs that we write. In such a case, commonly needed functions and macro definitions can be stored in a file and that file can be included wherever necessary.
81
Advance C Concepts

Conditional Compilation
 This feature

allows selective inclusion of lines of source text on the basis of computed condition.  Conditional compilation is performed using the preprocessor directives #ifdef #ifndef #elif #else #endif
82
Advance C Concepts

Error generation Error Generation


#

error token sequence  We can display the error message on occurrence of error.

User defined data types


 typedef type new-type  (Ex) typedef int

age;

83

Advance C Concepts

Enumerations
This provide the facility to specify the possible values of a variable by meaningful symbolic means. This can help the program more readable.  enum tag {member1, member2, ., member n};


84

Advance C Concepts

Unions
 Unions are

like structure, contain members whose individual data types may differ from one another.  However, the members that compose a union all share the same storage area within the computers memory, whereas each member within a structure is assigned its own unique storage area.  The compiler allocates sufficient memory to hold the Largest data item in the union.  The member variable of union can be accessed same way as a structures member variable are accessed.
85
Advance C Concepts

86

Advance C Concepts

Asynchronous communication
RS232 is

an asynchronous communication protocol It does not have a seperate clock signal The clock recovery is done by including a known transition event in the data,so as to synchronise the transmitter and the receiver

87

Advance C Concepts

Bit Timing and Bit Rate


The bit

time is the time from the start of one serial bit date to the start of another data. The inverse of bit time is the Baud rate RS-232 are integer multiples and sub multiples of 9600bps.

88

Advance C Concepts

Electrical Specification
The UART input/output 0V for

logic 0 and 5V for

logic 1. The RS-232 STANDARD uses +12v for logic 0 and -12V for logic 1 We convert this voltage levels by a level converter MAX232.

89

Advance C Concepts

Parts of RS-232 Frame


A FRAME

transmits a single character and is composed of: 1 start bit 8 data bits 1 stop bit 1 parity bit

90

Advance C Concepts

Hardware Proporties
Devices which use serial cables for their communication are split into two categories.  DCE (Data Communications Equipment) and DTE (Data Terminal Equipment.)  Data Communications Equipment are devices such as your modem  Data Terminal Equipment is the Computer or Terminal.

91
Advance C Concepts

Flow Control
Flow control has two basic types:Hardware and Software flow control.  Software flow control ,buffer will transmit the data, and the control is accompanied by xon/xoff bit.  Hardware flow control,two additional lines for RTS, CTS. When the terminal wants to be transmitted, pulls RTS high,dce sends the response back by sending CTS high.


92

Advance C Concepts

Programming Addresses and IRQ

NAME COM1 COM2 COM3 COM4

ADRESS 3F8 2F8 3E8 2E8

IRQ 4 3 4 3

93

Advance C Concepts

Serial Port Registers


The uart has only eight port address, but uart can able to access twelve registers with the help of dlab bit. Registers: Interrupt Enable Register (IER) Interrupt Identification Register (idr) First In/First Out Control Register (FCR) Line Control Register (LCR) Modem Control Register (MCR) Line Status Register (LSR) Modem Status Register (MSR) Transmitor holding buffer Receiver Buffer Divisor Latch Low Byte Divisor latch high byte Scratch register
94
Advance C Concepts

Interrupt Enable Registers


Bit Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0 Notes Reserved Reserved Enables Low Power Mode Enables Sleep Mode Enable Modem Status Interrupt Enable Receiver Line status Interrupt Enable Transmitter Holding Register Empty Interrupt Enable Received Data Available Interrupt

95

Advance C Concepts

Interrupt Identification Register identification register


Bit BIT 7:6 0 0 1 Bit 5 Bit 4 Bit 3 Bit 2:1 0 1 1 No FIFO FIFO Enabled but Unusable FIFO Enabled notes

Enable 64 Byte FIFO (16750 only) Reserved 0 1 0 0 1 1 Reserved on 8250, 16450 16550 Time-out Interrupt Pending 0 1 0 1 Modem Status Interrupt Transmitter Holding Register Empty Interrupt Received Data Available Interrupt Receiver Line Status Interrupt

Bit 0

0 0

Interrupt Pending No Interrupt Pending

96

Advance C Concepts

First in/First out control register


Bit Bit7 Notes 0 0 1 1 Bit5 Bit4 Bit3 Bit2 Bit1 0 1 0 1 Interrupt Trigger Level , 1 BYTE Interrupt Trigger Level , 4BYTE Interrupt Trigger Level , 8 BYTE Interrupt Trigger Level , 14BYTE

Enable 64 Byte FIFO (16750 only) RESERVED DMA Mode Select. Change status of RXRDY & TXRDY pins from mode 1 to mode 2. Clear Transmit FIFO Clear Receive FIFO

Bit0

Enable FIFO's

97

Advance C Concepts

LINE CONTROL Register Line Control REGISTER


Bit BIT 7 1 0 Bit 6 Bit 5 Bit 3:5 No FIFO FIFO Enabled but Unusable notes

Enable 64 Byte FIFO (16750 only) Reserved X X 0 NO PARITY

0 0 1 1 Bit 2 0 0

0 1 0 1

1 1 1 1

ODD PARITY EVEN PARITY HIGH PATITY LOW PARITY

1 STOP BIT 2 Stop bits for words of length 8 Bits

Bit 1:0

0 0 1 1

0 1 0 1

5 BITS 6 BITS 7 BITS 8 BITS 98


Advance C Concepts

Modem Control Register


Bit Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0 Notes Reserved Reserved
Auto flow Control Enabled (16750 only) Loop Back Mode Aux Output 2 Aux Output 1 Force Request to Send Force Data Terminal Ready

99

Advance C Concepts

Line Status Register


Bit Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0 Notes Error in received fifo
Empty Data Holding Registers Empty Transmitter Holding Register Break Interrupt Framing Error Parity Error Overrun error Data ready

10 0

Advance C Concepts

Modem Status REGISTER MODEM STATUS Register


Bit Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Notes Carrier Detect Ring Indicator Data Set Ready Clear To Send Delta Data Carrier Detect Trailing Edge Ring Indicator Delta Data Set Ready

Bit0

Delta Data Set Ready

10 1

Advance C Concepts

Programming Steps
two methods of programming. Polling : to see if the new data is available. Interrupts :an interrupt handler to remove the data from the uart when it generates an interrupt. Polling the UART is a lot slower method, which is very CPU intensive thus can only have a maximum speed of around 34.8 KBPS before you start losing data. The other option is using a Interrupt handler, and that's what we have used here. It will very easily support 115.2K BPS, even on low end computers.
10 2
Advance C Concepts

There are

Thank You

10 3

Advance C Concepts

You might also like