Sunteți pe pagina 1din 235

www.tutorialspoint.

com
C/C++
Tutorial
By alzanaty

Lesson 1

Program Structure

Program Structure
Consist of:

Preprocessor Commands

Functions

Variables

Statements & Expressions

Comments

Lesson 2
Basic syntax

Basic syntax

Tokens in C !" # $ # %& # ' ()

Semicolons % ' &: Statement terminator)

Comments: $$ or $* any+text *$ )

,dentifiers: is a name used to identify a -ariable# function)


%. to / or a to 0& # underscore % + & # follo1ed by number)

C is case sensiti-e )

23itespace in C : is allo1ed and not compiled)



Lesson 3
4ata Types

ata Types

T3e type of a -ariable determines 3o1 muc3 space it occupies


in storage and 3o1 t3e bit pattern stored is interpreted)
56 Basic Types: T3ey are arit3metic types and consists of t3e
t1o types: %a& integer types and %b& floating6point types)
76 Enumerated types: -ariables t3at can only be assigned
certain discrete integer -alues)
86 Void Type: not3ing)
96 4eri-ed types: T3ey include %a& Pointer types# %b& .rray
types# %c& Structure types# %d& :nion types and %e& Function
types)

!nteger Types
To get the exact size of a type or a variable on a particular platform,
The expressions sizeof(type) yields the storage size of the object or type in
bytes

"loating#Point Types
Minimum float positive value: FLT_MIN
Maximum float positive value: FLT_MAX
Precision value: FLT_DIG.
%E : to print big float numbers.

T$e %oi& Type

Function returns as void: do not return -alue


For example -oid exit %int status& )

Function arguments as void: do not accept any


parameter
int rand%-oid&)

Pointers to void: . pointer of type -oid * represents t3e


address of an ob;ect# but not its type For example a
memory allocation function -oid *malloc% si0e+t si0e &'
returns a pointer to -oid 13ic3 can be casted to any data
type)

Lesson '
Variables

(aria)les

A variable:
is not3ing but a name gi-en to a storage area t3at our
programs can manipulate) Eac3 -ariable in C 3as a
specific type# 13ic3 determines t3e si0e and layout of t3e
-ariable<s memory' t3e range of -alues t3at can be stored
1it3in t3at memory' and t3e set of operations t3at can be
applied to t3e -ariable)

(aria)les
Declaration:
Type variable_name = value;

(aria)les

For definition 1it3out an initiali0er: -ariables 1it3 static storage


duration are implicitly initiali0ed 1it3 =:>> %all bytes 3a-e t3e
-alue ?&' t3e initial -alue of all ot3er -ariables is undefined)

. -ariable declaration 3as its meaning at t3e time of compilation


only# compiler needs actual -ariable declaration at t3e time of
linking of t3e program)

. -ariable declaration is useful 13en you are using multiple files


and you define your -ariable in one of t3e files 13ic3 1ill be
a-ailable at t3e time of linking of t3e program) @ou 1ill use extern
key1ord to declare a -ariable at any place) T3oug3 you can
declare a -ariable multiple times in your C program but it can be
defined only once in a file# a function or a block of code)

(aria)les

(aria)les

Lvalues and Rvalues in C:


>-alue: memory location is called Al-alueA expression)
B-alue: r-alue refers to a data -alue t3at is stored at some
address in memory)

Lesson *
Constant

Constant

T3e constants refer to fixed -alues t3at t3e program may


not alter during its execution T3ese fixed -alues are also
called literals)

Constants can be any basic types or enumerated types)



Constant

Integer literals: can be a decimal# octal# or 3exadecimal


constant) . prefix specifies t3e base or radix: ?x or ?C for
3exadecimal# ? for octal# and not3ing for decimal# can also
3a-e a suffix t3at is a combination of : and ># for unsigned
and long)

Constant

Floating-point literals:
. floating6point literal 3as an integer part# a decimal point# a
fractional part# and an exponent part)
23ile representing using decimal form# you must include t3e
decimal point# t3e exponent# or bot3 and 13ile representing
using exponential form# you must include t3e integer part# t3e
fractional part# or bot3) T3e signed exponent is introduced by e
or E)

Constant

Character literals: are enclosed in single Duotes# e)g)# <x<


and can be stored in a simple -ariable of c3ar type)

Constant

String literals: String literals or constants are enclosed in


double Duotes AA) . string contains c3aracters t3at are
similar to c3aracter literals: plain c3aracters# escape
seDuences# and uni-ersal c3aracters) @ou can break a
long line into multiple lines using string literals and
separating t3em using 13itespace) Eere are some
examples of string literals) .ll t3e t3ree forms are identical
strings)

e+ining Constants

T3ere are t1o simple 1ays in C to define constants:


56:sing Fdefine preprocessor)
76:sing const key1ord)

T3e Fdefine Preprocessor


Follo1ing is t3e form to use Fdefine preprocessor to define a constant:
Fdefine identifier -alue

@ou can use const prefix to declare constants 1it3 a specific type as
follo1s:
const type -ariable G -alue'

e+ining Constants ,xample

e+ining Constants ,xample

Lesson -
Storage Classes

Storage Classes

A storage class defines t3e scope %-isibility& and life6time


of -ariables andHor functions 1it3in a C Program)

T3ere are t3e follo1ing storage classes# 13ic3 can be


used in a C Program
56 auto)
76 register)
86 static)
96 extern)

T$e auto Storage Class
T3e auto storage class is t3e default storage class for all local
-ariables)

int mount'
auto int mont3'
(
T3e example abo-e defines t1o -ariables 1it3 t3e same storage
class# auto can only be used 1it3in functions# i)e)# local -ariables)

T$e register Storage Class

T3e register storage class is used to define local -ariables


t3at s3ould be stored in a register instead of B.I)

T3is means t3at t3e -ariable 3as a maximum si0e eDual to


t3e register si0e %usually one 1ord& and can<t 3a-e t3e
unary <&< operator applied to it %as it does not 3a-e a
memory location&)

register int miles'


(

T$e register Storage Class

T3e register s3ould only be used for -ariables t3at reDuire


Duick access suc3 as counters) ,t s3ould also be noted
t3at defining <register< does not mean t3at t3e -ariable 1ill
be stored in a register) ,t means t3at it I,JET be stored in
a register depending on 3ard1are and implementation
restrictions)

T$e static Storage Class

T3e static storage class instructs t3e compiler to keep a local


-ariable in existence during t3e life6time of t3e program instead
of creating and destroying it eac3 time it comes into and goes
out of scope) T3erefore# making local -ariables static allo1s
t3em to maintain t3eir -alues bet1een function calls)

T3e static modifier may also be applied to global -ariables)


23en t3is is done# it causes t3at -ariable<s scope to be
restricted to t3e file in 13ic3 it is declared)

,n C programming# 13en static is used on a class data member#


it causes only one copy of t3at member to be s3ared by all
ob;ects of its class)

T$e static Storage Class

T$e extern Storage Class

The extern storage class is used to gi-e a reference of a global variable


t3at is -isible to .>> t3e program files) 23en you use <extern<# t3e
-ariable cannot be initiali0ed# as all it does is point t3e -ariable name at a
storage location t3at 3as been pre-iously defined)

23en you 3a-e multiple files and you define a global -ariable or function#
13ic3 1ill be used in ot3er files also# t3en extern 1ill be used in anot3er
file to gi-e reference of defined -ariable or function) Kust for
understanding# extern is used to declare a global -ariable or function in
anot3er file)

T3e extern modifier is most commonly used 13en t3ere are t1o or more
files s3aring t3e same global -ariables or functions as explained belo1)

T$e extern Storage Class

Lesson .
Lperators

/perators

An operator is a symbol t3at tells t3e compiler to perform


specific mat3ematical or logical manipulations)

types of operators:
56 .rit3metic Lperators)
76 Belational Lperators)
86 >ogical Lperators)
96 Bit1ise Lperators)
M6 .ssignment Lperators)
N6 Iisc Lperators)

0rit$metic /perators

1elational /perators

Logical /perators

Bitwise /perators

0ssignment /perators

2isc /perators sizeo+ 3 ternary

2isc /perators sizeo+ 3 ternary

/perators Prece&ence in C

Lesson .
4ecision Iaking

ecision 2a4ing

4ecision making structures reDuire t3at t3e programmer


specify one or more conditions to be e-aluated or tested
by t3e program)

C assumes any non60ero and non6null -alues as true# and


if it is eit3er 0ero or null# t3en it is assumed as false -alue)

T$e 5 6 /perator

4efinition:
Exp5 O Exp7 : Exp8'

T3e -alue of a O expression is determined like t3is: Exp5 is


e-aluated) ,f it is true# t3en Exp7 is e-aluated and
becomes t3e -alue of t3e entire O expression) ,f Exp5 is
false# t3en Exp8 is e-aluated and its -alue becomes t3e
-alue of t3e expression)

!+ Statment
Syntax:
T3e syntax of an if statement in C programming language is:
if%boolean+expression&

H* statement%s& 1ill execute if t3e boolean expression is


true*H
(

!+ else Statment
Syntax:
T3e syntax of an if)))else statement in C programming language is:
if%boolean+expression&

H* statement%s& 1ill execute if t3e boolean expression is true *H


(
else

H* statement%s& 1ill execute if t3e boolean expression is false *H


(

neste& i+ statements
if% boolean+expression 5&

H* Executes 13en t3e boolean expression 5 is true *H


if%boolean+expression 7&

H* Executes 13en t3e boolean expression 7 is true *H
(
(

Switc$ statement
s1itc3%expression&
case constant6expression :
statement%s&'
break' H* optional *H
case constant6expression :
statement%s&'
break' H* optional *H
H* you can 3a-e any number of case statements *H
default : H* Lptional *H
statement%s&' (

neste& switc$ statements
s1itc3%c35&
case <.<:
printf%AT3is . is part of outer s1itc3A &'
s1itc3%c37&
case <.<:
printf%AT3is . is part of inner s1itc3A &'
break'
case <B<: H* case code *H
(
break'
case <B<: H* case code *H
(

Lesson 7
>oops

A loop statement allo1s us to execute a statement or


group of statements multiple times and follo1ing is t3e
general form of a loop statement in most of t3e
programming languages:

w$ile loop in C

Syntax:
T3e syntax of a 13ile loop in C programming language is:
13ile%condition&

statement%s&'
(

Eere# statements! may be a single statement or a block of


statements) T3e condition may be any expression# and true is any
non0ero -alue) T3e loop iterates 13ile t3e condition is true)

"or Loop
for % init' condition' increment &

statement%s&'
(

&o...w$ile loop

:nlike for and 13ile loops# 13ic3 test t3e loop condition at
t3e top of t3e loop# t3e do)))13ile loop in C programming
language c3ecks its condition at t3e bottom of t3e loop)

Syntax:
do

statement%s&'
(13ile% condition &'

neste& +or loops

T3e syntax for a nested for loop statement in C is as follo1s:


for % init' condition' increment &

for % init' condition' increment &



statement%s&'
(
statement%s&'
(

neste& w$ile loop

Syntax:
13ile%condition&

13ile%condition&

statement%s&'
(
statement%s&'
(

neste& &o...w$ile loop
do

statement%s&'
do

statement%s&'
(13ile% condition &'
(13ile% condition &'

Loop Control Statements6

Loop control statements c3ange execution from its


normal seDuence) 23en execution lea-es a scope# all
automatic ob;ects t3at 1ere created in t3at scope are
destroyed)

)rea4 statement

T3e break statement 3as t3e follo1ing t1o usages:


5623en t3e break statement is encountered inside a loop# t3e loop is
immediately terminated and program control resumes at t3e next
statement follo1ing t3e loop)
76,t can be used to terminate a case in t3e s1itc3 statement)
,f you are using nested loops# t3e break statement 1ill stop t3e execution
of t3e innermost loop and start executing t3e next line of code after t3e
block)

Syntax:
T3e syntax for a break statement in C is as follo1s:
break'

continue statement

T3e continue statement in C programming language 1orks


some13at like t3e break statement) ,nstead of forcing
termination# 3o1e-er# continue forces t3e next iteration of
t3e loop to take place# skipping any code in bet1een)

For t3e for loop# continue statement causes t3e conditional


test and increment portions of t3e loop to execute) For t3e
13ile and do)))13ile loops# continue statement causes t3e
program control passes to t3e conditional tests)

Syntax:
continue'

goto statement

. goto statement in C programming language pro-ides an unconditional


;ump from t3e goto to a labeled statement in t3e same function)

=LTE: :se of goto statement is 3ig3ly discouraged in any programming


language because it makes difficult to trace t3e control flo1 of a program#
making t3e program 3ard to understand and 3ard to modify) .ny program
t3at uses a goto can be re1ritten so t3at it doesn<t need t3e goto)

Syntax:
goto label'
))
)
label: statement'

,xample go to

T$e !n+inite Loop

. loop becomes infinite loop if a condition ne-er becomes


false) T3e for loop is traditionally used for t3is purpose)
Since none of t3e t3ree expressions t3at form t3e for loop
are reDuired# you can make an endless loop by lea-ing t3e
conditional expression empty)

Syntax:
for% ' ' &

=LTE: @ou can terminate an infinite loop by pressing


Ctrl P C keys)

Lesson 8
Functions

"unctions

A "unction is a group of statements t3at toget3er perform


a task) E-ery C program 3as at least one function# 13ic3 is
main%&# and all t3e most tri-ial programs can define
additional functions)

. function declaration tells t3e compiler about a function<s


name# return type# and parameters) . function definition
pro-ides t3e actual body of t3e function)

T3e C standard library pro-ides numerous built6in


functions t3at your program can call)

e+ining a "unction
return+type function+name% parameter list &

body of t3e function


(

Return T#pe: . function may return a -alue)

Function $ame: T3is is t3e actual name of t3e function)

Parameters: . parameter is like a place3older)

Function %od#: T3e function body contains a collection of


statements t3at define 13at t3e function does)

"unction eclarations

. function declaration tells t3e compiler about a function


name and 3o1 to call t3e function) T3e actual body of t3e
function can be defined separately)

. function declaration 3as t3e follo1ing parts:


return+type function+name% parameter list &'

"unction 0rguments6

Call )y %alue

T3e call by -alue met3od of passing arguments to a


function copies t3e actual -alue of an argument into t3e
formal parameter of t3e function) ,n t3is case# c3anges
made to t3e parameter inside t3e function 3a-e no effect
on t3e argument)

By default# C programming language uses call by -alue


met3od to pass arguments)

Call )y re+erence

T3e call by reference met3od of passing arguments to a


function copies t3e address of an argument into t3e formal
parameter) ,nside t3e function# t3e address is used to
access t3e actual argument used in t3e call) T3is means
t3at c3anges made to t3e parameter affect t3e passed
argument)

To pass t3e -alue by reference# argument pointers are


passed to t3e functions ;ust like any ot3er -alue)
-oid s1ap%int *x# int *y&

Lesson 19
Scope Bules

Scope 1ules

A scope in any programming is a region of t3e program 13ere


a defined -ariable can 3a-e its existence and beyond t3at
-ariable can not be accessed)

T3ere are three places 13ere -ariables can be declared in C


programming language:
56,nside a function or a block 13ic3 is called local -ariables#
76Lutside of all functions 13ic3 is called global -ariables)
86,n t3e definition of function parameters 13ic3 is called
formal parameters)

Local (aria)les

Variables t3at are declared inside a function or block are


called local -ariables) T3ey can be used only by
statements t3at are inside t3at function or block of code)
>ocal -ariables are not kno1n to functions outside t3eir
o1n)

:lo)al (aria)les

Jlobal -ariables are defined outside of a function# usually


on top of t3e program) T3e global -ariables 1ill 3old t3eir
-alue t3roug3out t3e lifetime of your program and t3ey can
be accessed inside any of t3e functions defined for t3e
program)

. global -ariable can be accessed by any function) T3at is#


a global -ariable is a-ailable for use t3roug3out your entire
program after its declaration)

!nitializing Local an& :lo)al (aria)les

23en a local -ariable is defined# it is not initiali0ed by t3e


system# you must initiali0e it yourself) Jlobal -ariables are
initiali0ed automatically by t3e system 13en you define
t3em as follo1s:

Lesson 11
.rrays

e+inition6

C pro-ides a data structure called t3e arra## 13ic3 can


store a fixed6si0e seDuential collection of elements of t3e
same type) .n array is used to store a collection of data#
but it is often more useful to t3ink of an array as a
collection of -ariables of t3e same type)

.ll arrays consist of contiguous memory locations) T3e


lo1est address corresponds to t3e first element and t3e
3ig3est address to t3e last element)

e+inition6

To declare an array in C# a programmer specifies t3e type


of t3e elements and t3e number of elements reDuired by
an array as follo1s:
type array=ame Q arraySi0e R'

T3is is called a single6dimensional array) T3e arraySi0e


must be an integer constant greater t3an 0ero and type
can be any -alid C data type)

!nitializing 0rrays

@ou can initiali0e array in C eit3er one by one or using a


single statement as follo1s:
double balanceQMR G 5???)?# 7)?# 8)9# S)?# M?)?('

,f you omit t3e si0e of t3e array# an array ;ust big enoug3 to
3old t3e initiali0ation is created) T3erefore# if you 1rite:
double balanceQR G 5???)?# 7)?# 8)9# S)?# M?)?('

.n element is accessed by indexing t3e array name:


double salary G balanceQTR'

2ulti#&imensional 0rrays

C programming language allo1s multidimensional arrays)


Eere is t3e general form of a multidimensional array
declaration:
type name Qsi0e5RQsi0e7R)))Qsi0e=R'

For example# t3e follo1ing declaration creates a t3ree


dimensional M ) 5? ) 9 integer array:
int t3reedimQMRQ5?RQ9R'

Two#imensional 0rrays

type array=ame Q x RQ y R'

. t1o6dimensional array can be t3ink as a table 13ic3 1ill


3a-e x number of ro1s and y number of columns)

int -al G aQ7RQ8R'



Passing 0rrays as "unction 0rguments

2ay65
Formal parameters as a pointer as follo1s)

-oid myFunction%int *param&

)
)
)
(

Passing 0rrays as "unction 0rguments

2ay67
Formal parameters as a si0ed array as follo1s:
-oid myFunction%int paramQ5?R&

)
)
)
(

Passing 0rrays as "unction 0rguments

2ay68
Formal parameters as an unsi0ed array as follo1s:
-oid myFunction%int paramQR&

)
)
)
(

,xample

,xample Con....

1eturn array +rom +unction

C programming language does not allo1 to return an entire array as


an argument to a function) Eo1e-er# you can return a pointer to an
array by specifying t3e array<s name 1it3out an index)

,f you 1ant to return a single6dimension array from a function# you


1ould 3a-e to declare a function returning a pointer as in t3e follo1ing
example:
int * myFunction%&

(

1eturn array +rom +unction

Second point to remember is t3at C does not ad-ocate to


return t3e address of a local -ariable to outside of t3e
function so you 1ould 3a-e to define t3e local -ariable as
static -ariable)

1eturn array +rom +unction

Pointer to an 0rray

.n array name is a constant pointer to t3e first element of


t3e array) T3erefore# in t3e declaration:
double balanceQM?R'

balance is a pointer to &balanceQ?R# 13ic3 is t3e address of


t3e first element of t3e array balance)

,t is legal to use array names as constant pointers# and -ice


-ersa) T3erefore# *%balance P 9& is a legitimate 1ay of
accessing t3e data at balanceQ9R)

Lnce you store t3e address of first element in p# you can


access array elements using *p# *%pP5&# *%pP7& and so on)

,xample Pointer to an 0rray

,xample Pointer to an 0rray
In the above example, p is a pointer to double,
which means it can store address of a variable of double type.
Once we have address in p,
then *p will give us value available at the address stored in p,
as we have shown in the above example.

Lesson 11
Pointers

e+inition

Pointers in C are easy and fun to learn) Some C


programming tasks are performed more easily 1it3
pointers# and ot3er tasks# suc3 as dynamic memory
allocation# cannot be performed 1it3out using pointers) So
it becomes necessary to learn pointers to become a
perfect C programmer)

.s you kno1# e-ery -ariable is a memory location and


e-ery memory location 3as its address defined 13ic3 can
be accessed using ampersand %&& operator# 13ic3 denotes
an address in memory)

;$at 0re Pointers5

. pointer is a -ariable 13ose -alue is t3e address of anot3er -ariable#


i)e)# direct address of t3e memory location) >ike any -ariable or
constant# you must declare a pointer before you can use it to store any
-ariable address) T3e general form of a pointer -ariable declaration is:
type *-ar6name'

Eo1e-er# in t3is statement t3e asterisk is being used to designate a


-ariable as a pointer)

T3e actual data type of t3e -alue of all pointers# 13et3er integer# float#
c3aracter# or ot3er1ise# is t3e same# a long 3exadecimal number t3at
represents a memory address) T3e only difference bet1een pointers of
different data types is t3e data type of t3e -ariable or constant t3at t3e
pointer points to)

<ow to use Pointers5

T3ere are fe1 important operations# 13ic3 1e 1ill do 1it3


t3e 3elp of pointers -ery freDuently) %a& 1e define a pointer
-ariable %b& assign t3e address of a -ariable to a pointer and
%c& finally access t3e -alue at t3e address a-ailable in t3e
pointer -ariable) T3is is done by using unary operator * t3at
returns t3e -alue of t3e -ariable located at t3e address
specified by its operand)

,t is al1ays a good practice to assign a =:>> -alue to a


pointer -ariable in case you do not 3a-e exact address to be
assigned) T3is is done at t3e time of -ariable declaration) .
pointer t3at is assigned =:>> is called a null pointer)

Pointer arit$metic

C pointer is an address# 13ic3 is a numeric -alue)


T3erefore# you can perform arit3metic operations on a
pointer ;ust as you can a numeric -alue) T3ere are four
arit3metic operators t3at can be used on pointers: PP# 66# P#
and 6 )

To understand pointer arit3metic# let us consider t3at ptr is


an integer pointer 13ic3 points to t3e address 5???)
.ssuming 876bit integers# let us perform t3e follo1ing
arit3metic operation on t3e pointer:
ptrPP

Pointer arit$metic

=o1# after t3e abo-e operation# t3e ptr 1ill point to t3e
location 5??9 because eac3 time ptr is incremented# it 1ill
point to t3e next integer location 13ic3 is 9 bytes next to
t3e current location) T3is operation 1ill mo-e t3e pointer to
next memory location 1it3out impacting actual -alue at t3e
memory location) ,f ptr points to a c3aracter 13ose
address is 5???# t3en abo-e operation 1ill point to t3e
location 5??5 because next c3aracter 1ill be a-ailable at
5??5)

!ncrementing a Pointer

2e prefer using a pointer in our program instead of an


array because t3e -ariable pointer can be incremented#
unlike t3e array name 13ic3 cannot be incremented
because it is a constant pointer)

,xample o+ increment

Solution o+ ,xample

ecrementing a Pointer

ecrementing a Pointer
The same considerations apply to decrementing a pointer,
which decreases its value by the number of bytes

Pointer Comparisons

Pointers may be compared by using relational operators#


suc3 as GG# U# and V )

,f p5 and p7 point to -ariables t3at are related to eac3


ot3er# suc3 as elements of t3e same array# t3en p5 and p7
can be meaningfully compared)

Pointer Comparisons ,xample

Pointer to an 0rray
double balanceQM?R'
balance is a pointer to &balanceQ?R# 13ic3 is t3e address of
t3e first element of t3e array balance) T3us# t3e follo1ing
program fragment assigns p t3e address of t3e first element
of balance:
double *p'
double balanceQ5?R'
p G balance'

Pointer to an 0rray
,t is legal to use array names as constant pointers# and -ice
-ersa) T3erefore# *%balance P 9& is a legitimate 1ay of
accessing t3e data at balanceQ9R)
Lnce you store t3e address of first element in p# you can
access array elements using *p# *%pP5&# *%pP7& and so on)

0rray o+ pointers

T3ere may be a situation 13en 1e 1ant to maintain an


array# 13ic3 can store pointers to an int or c3ar or any
ot3er data type a-ailable) Follo1ing is t3e declaration of an
array of pointers to an integer:
int *ptrQI.CR'

T3is declares ptr as an array of I.C integer pointers)


T3us# eac3 element in ptr# no1 3olds a pointer to an int
-alue)

0rray o+ pointers ,xample

0rray o+ pointers ,xample

0rray o+ pointers ,xample

0rray o+ pointers ,xample

Pointer to Pointer

. pointer to a pointer is a form of multiple indirection# or a


c3ain of pointers)

=ormally# a pointer contains t3e address of a -ariable)


23en 1e define a pointer to a pointer# t3e first pointer
contains t3e address of t3e second pointer#

Pointer to Pointer

. -ariable t3at is a pointer to a pointer must be declared as


suc3) T3is is done by placing an additional asterisk in front
of its name

For example# follo1ing is t3e declaration to declare a


pointer to a pointer of type int:
int **-ar'

23en a target -alue is indirectly pointed to by a pointer to


a pointer# accessing t3at -alue reDuires t3at t3e asterisk
operator be applied t1ice)

Pointer to Pointer ,xample

Passing pointers to +unctions

C programming language allo1s you to pass a pointer to a


function) To do so# simply declare t3e function parameter
as a pointer type)

1eturn pointer +rom +unctions

.s 1e 3a-e seen in last c3apter 3o1 C programming


language allo1s to return an array from a function# similar
1ay C allo1s you to return a pointer from a function)

Second point to remember is t3at# it is not good idea to


return t3e address of a local -ariable to outside of t3e
function so you 1ould 3a-e to define t3e local -ariable as
static -ariable)

Lesson 12
Strings

e+inition

T3e string in is actually a one6dimensional array of


c3aracters 13ic3 is terminated by a null c3aracter <$?< )
c3ar greetingQNR G <E<# <e<# <l<# <l<# <o<# <$?<('
or
c3ar greetingQR G AEelloA'

e+initions

.ctually# you do not place t3e null c3aracter at t3e end of a


string constant) T3e C compiler automatically places t3e
<$?< at t3e end of t3e string 13en it initiali0es t3e array)

+unctions t$at &eal wit$ Strings

Lesson 13
Structures

Structures

C arrays allo1 you to define type of -ariables t3at can 3old se-eral
data items of t3e same kind but structure is anot3er user defined
data type a-ailable in C programming# 13ic3 allo1s you to combine
data items of different kinds)

Structures are used to represent a record# Suppose you 1ant to


keep track of your books in a library) @ou mig3t 1ant to track t3e
follo1ing attributes about eac3 book:

Title

.ut3or

Sub;ect

Book ,4

e+ining a Structure

To define a structure# you must use t3e struct statement)


T3e struct statement defines a ne1 data type# 1it3 more
t3an one member for your program)

struct Qstructure tagR

member definition'

member definition'

)))

member definition'

( Qone or more structure -ariablesR'



e+ining a Structure

T3e structure tag is optional and eac3 member definition is a


normal -ariable definition# suc3 as int i' or float f' or any ot3er -alid
-ariable definition)

.t t3e end of t3e structure<s definition# before t3e final semicolon#


you can specify one or more structure -ariables but it is optional)

struct Books
c3ar titleQM?R'
c3ar aut3orQM?R'
c3ar sub;ectQ5??R'
int book+id'
( book'

0ccessing Structure 2em)ers

To access any member of a structure# 1e use t3e member


access operator %)& # T3e member access operator is
coded as a period bet1een t3e structure -ariable name
and t3e structure member t3at 1e 1is3 to access)

@ou 1ould use struct key1ord to define -ariables of


structure type)

Structures as "unction 0rguments

@ou can pass a structure as a function argument in -ery


similar 1ay as you pass any ot3er -ariable or pointer)

.nd access t3em by %)& operator)



Pointers to Structures

@ou can define pointers to structures in -ery similar 1ay as


you define pointer to any ot3er -ariable as follo1s:
struct %oo&s 'struct(pointer)

=o1# you can store t3e address of a structure -ariable in


t3e abo-e defined pointer -ariable)

To find t3e address of a structure -ariable# place t3e &


operator before t3e structure<s name:
struct+pointer G &Book5'

To access t3e members of a structure using a pointer to


t3at structure# you must use t3e 6V operator as follo1s:
struct+pointer6Vtitle'

Bit "iel&s

Bit Fields allo1 t3e packing of data in a structure) T3is is


especially useful 13en memory or data storage is at a
premium) Typical examples:

Packing se-eral ob;ects into a mac3ine 1ord) e)g) 5 bit


flags can be compacted)

Beading external file formats 66 non6standard file


formats could be read in) E)g) T bit integers)

Bit "iel&s

C allo1s us do t3is in a structure definition by putting :bit lengt3 after t3e


-ariable) For example:
struct packed+struct
unsigned int f5:5'
unsigned int f7:5'
unsigned int f8:5'
unsigned int f9:5'
unsigned int type:9'
unsigned int my+int:T'
( pack'
Eere# t3e packed+struct contains N members: Four 5 bit flags f5))f8# a 9 bit
type and a T bit my+int)

Bit "iel&s

C automatically packs t3e abo-e bit fields as compactly as


possible# pro-ided t3at t3e maximum lengt3 of t3e field is
less t3an or eDual to t3e integer 1ord lengt3 of t3e
computer)

,f t3is is not t3e case t3en some compilers may allo1


memory o-erlap for t3e fields 13ilst ot3er 1ould store t3e
next field in t3e next 1ord)

Lesson 1'
:nions

=nions

. union is a special data type a-ailable in C t3at enables


you to store different data types in t3e same memory
location)

@ou can define a union 1it3 many members# but only one
member can contain a -alue at any gi-en time)

:nions pro-ide an efficient 1ay of using t3e same memory


location for multi6purpose)

e+ining a =nion

To define a union# you must use t3e union statement in -ery similar
1as as you did 13ile defining structure)

T3e union statement defines a ne1 data type# 1it3 more t3an one
member for your program)
union Qunion tagR
member definition'
member definition'
))
member definition'
( Qone or more union -ariablesR'

e+ining a =nion

T3e union tag is optional and eac3 member definition is a normal


-ariable definition# suc3 as int i' or float f' or any ot3er -alid -ariable
definition)

.t t3e end of t3e union<s definition# before t3e final semicolon# you can
specify one or more union -ariables but it is optional)
union 4ata
int i'
float f'
c3ar strQ7?R'
( data'

e+ining a =nion

=o1# a -ariable of 4ata type can store an integer# a floating6point


number# or a string of c3aracters)

T3is means t3at a single -ariable ie) same memory location can
be used to store multiple types of data)

@ou can use any built6in or user defined data types inside a
union based on your reDuirement)

T3e memory occupied by a union 1ill be large enoug3 to 3old


t3e largest member of t3e union)

,n pre-ious example 4ata type 1ill occupy 7? bytes of memory


space because t3is is t3e maximum space 13ic3 can be
occupied by c3aracter string)

0ccessing =nion 2em)ers

To access any member of a union# 1e use t3e member


access operator %)&

T3e member access operator is coded as a period


bet1een t3e union -ariable name and t3e union member
t3at 1e 1is3 to access)

@ou 1ould use union key1ord to define -ariables of union


type)

=nion ,xample

=nion ,xample

Lesson 1*
Bit Fields

e+inition

T3e C programming language offers a better 1ay to utili0e t3e


memory space in suc3 situation)

,f you are using suc3 -ariables inside a structure t3en you can
define t3e 1idt3 of a -ariable 13ic3 tells t3e C compiler t3at you
are going to use only t3ose number of bytes)

struct

unsigned int 1idt3Validated : 5'


unsigned int 3eig3tValidated : 5'
( status'

e+inition

T3e pre-ious Struct 1ill reDuire 9 bytes of memory space


for status -ariable but only 7 bits 1ill be used to store t3e
-alues)

,f you 1ill use up to 87 -ariables eac3 one 1it3 a 1idt3 of 5


bit # t3en also status structure 1ill use 9 bytes)

but as soon as you 1ill 3a-e 88 -ariables# t3en it 1ill


allocate next slot of t3e memory and it 1ill start using W
bytes)

Bit "iel& eclaration

T3e declaration of a bit6field 3as t3e form inside a


structure:
struct

type Qmember+nameR : 1idt3 '


('

Bit "iel& eclaration

T3e -ariables defined 1it3 a predefined 1idt3 are called bit fields) .
bit field can 3old more t3an a single bit for example if you need a
-ariable to store a -alue from ? to S only t3en you can define a bit
field 1it3 a 1idt3 of 8 bits as follo1s:
struct

unsigned int age : 8'


( .ge'

T3e abo-e structure definition instructs C compiler t3at age -ariable


is going to use only 8 bits to store t3e -alue# if you 1ill try to use
more t3an 8 bits t3en it 1ill not allo1 you to do so)

Lesson 1-
typedef

Concept

T3e C programming language pro-ides a key1ord called


typedef# 13ic3 you can use to gi-e a type a ne1 name)

Follo1ing is an example to define a term B@TE for one6


byte numbers:
typedef unsigned c3ar B@TE'

.fter t3is type definitions# t3e identifier B@TE can be used


as an abbre-iation for t3e type unsigned c3ar# for example:
B@TE b5# b7'

Concept

By con-ention# uppercase letters are used for t3ese


definitions to remind t3e user t3at t3e type name is really a
symbolic abbre-iation# but you can use lo1ercase# as
follo1s:
typedef unsigned c3ar byte'

@ou can use typedef to gi-e a name to user defined data


type as 1ell)

For example you can use typedef 1it3 structure to define


a ne1 data type and t3en use t3at data type to define
structure -ariables directly)

type&e+ %s >&e+ine

T3e Fdefine is a C6directi-e 13ic3 is also used to define


t3e aliases for -arious data types similar to typedef but
1it3 follo1ing differences:

T3e typedef is limited to gi-ing symbolic names to types


only 13ere as Fdefine can be used to define alias for
-alues as 1ell# like you can define 5 as L=E etc)

T3e typedef interpretation is performed by t3e compiler


13ere as Fdefine statements are processed by t3e
preprocessor)

Lesson 1.
,nput & Lutput

Concept

23en 1e are saying ,nput t3at means to feed some data into
program) T3is can be gi-en in t3e form of file or from
command line)

C programming language pro-ides a set of built6in functions to


read gi-en input and feed it to t3e program as per
reDuirement)

23en 1e are saying Lutput t3at means to display some data


on screen# printer or in any file)

C programming language pro-ides a set of built6in functions to


output t3e data on t3e computer screen as 1ell as you can
sa-e t3at data in text or binary files)

T$e Stan&ar& "iles

C programming language treats all t3e de-ices as files) So de-ices suc3 as


t3e display are addressed in t3e same 1ay as files and follo1ing t3ree file
are automatically opened 13en a program executes to pro-ide access to
t3e keyboard and screen)

T3e file points are t3e means to access t3e file for reading and 1riting
purpose) T3is section 1ill explain you 3o1 to read -alues from t3e screen
and 3o1 to print t3e result on t3e screen)

T$e getc$ar?@ 3 putc$ar?@ +unctions

T3e int getcharvoid! function reads t3e next a-ailable


c3aracter from t3e screen and returns it as an integer) T3is
function reads only single c3aracter at a time) @ou can use
t3is met3od in t3e loop in case you 1ant to read more t3an
one c3aracters from t3e screen)

T3e int putcharint c! function puts t3e passed c3aracter


on t3e screen and returns t3e same c3aracter) T3is
function puts only single c3aracter at a time) @ou can use
t3is met3od in t3e loop in case you 1ant to display more
t3an one c3aracter on t3e screen)

,xample

T$e gets?@ 3 puts?@ +unctions

T3e char 'getschar 's! function reads a line from stdin


into t3e buffer pointed to by s until eit3er a terminating
ne1line or ELF)

T3e int puts%const c3ar *s& function 1rites t3e string s and
a trailing ne1line to stdout)

,xample

T$e scan+?@ an& print+?@ +unctions

( * , ...) The int scanf const char format function reads input from
the standard input stream stdin and scans that input according
. to format provided

( * , ...) The int printf const char format function writes output to
the standard output stream stdout and produces output
. according to a format provided

, The format can be a simple constant string but you can specify
% , % , % , % , ., , , s d c f etc to print or read strings integer character or
. foat respectively There are many other formatting options
. available which can be used based on requirements For a
. complete detail you can refer to a man page for these function

, () Here it should be noted that scanf expect input in


% % , the same format as you provided s and d which
" means you have to provide valid input like string
", " " " integer if you provide string string or integer
" . integer then it will be assumed as wrong input
, () Second while reading a string scanf stops reading
" " as soon as it encounters a space so this is test are
(). three strings for scanf

Lesson 17
File ,HL

Concept

, , How C programmers can create open close text or


. binary les for their data storage

, ! le represents a sequence of bytes does not


. matter if it is a text le or binary le

C programming language provides access on high


( ) level functions as well as low level "S level calls to
. handle le on your storage devices

/pening "iles

#ou can use the ( ) fopen function to create a new


, le or to open an existing le this call will initiali$e
, an ob%ect of the type F&'( which contains all the
. information necessary to control the stream

: Following is the prototype of this function call


* ( * , * ); FILE fopen const char flename const char mode

, , Here lename is string literal which you will use to


name your le and access mode can have one of
: the following values

/pening "iles
&f you are going to handle binary les then you will use
below mentioned access modes instead of the above
: mentioned
" ", " ", " ", " +", " + ", " +", " + ", " +", " + " rb wb ab rb r b wb w b ab a b

Closing a "ile

, To close a le use the ( ) fclose . function The prototype of this


: function is
( * ); int fclose FILE fp

The ( ) fclose , function returns $ero on success or ("F if there is


. an error in closing the le

, This function actually fushes any data still pending in the bu)er
, , to the le closes the le and releases any memory used for the
. le

( . ) . The ("F is a constant dened in the header le stdio h

There are various functions provide by C standard library to read


and write a le character by character or in the form of a xed
. . length string 'et us see few of the in the next section

;riting a "ile

Following is the simplest function to write individual


: characters to a stream
( , * ); int fputc int c FILE fp

The function () fputc writes the character value of the


. argument c to the output stream referenced by fp &t returns
the written character written on success otherwise ("F if
. there is an error

- #ou can use the following functions to write a null terminated


: string to a stream
( * , * ); int fputs const char s FILE fp

;riting a "ile

The function () fputs writes the string s to the


. - output stream referenced by fp &t returns a non
, negative value on success otherwise ("F is
. returned in case of any error

#ou can use ( * , int fprintf FILE fp const char


* , ...) format function as well to write a string into a
. le

1ea&ing a "ile

Following is the simplest function to read a single


: character from a le
( * ); int fgetc FILE fp

The () fgetc function reads a character from the input


. le referenced by fp The return value is the character
, . read or in case of any error it returns ("F

The following functions allow you to read a string from a


: stream
* ( * , , * ); char fgets char buf int n FILE fp

1ea&ing a "ile

The functions () fgets - 1 reads up to n characters


. from the input stream referenced by fp &t copies the
read string into the bu)er buf, appending a null
. character to terminate the string

'\ ' &f this function encounters a newline character n


or the end of the le ("F before they have read the
, maximum number of characters then it returns
only the characters read up to that point including
. new line character

1ea&ing a "ile

#ou can also use int ( * , fscanf FILE fp const char


* , ...) format function to read strings from a le but it
stops reading after the rst space character
. encounters

' 'et s see a little more detail about what happened


. here First () fscanf method read %ust This because
, after that it encountered a space second call is for
() fgets which read the remaining line till it
. encountered end of line Finally last call () fgets read
. second line completely

Binary !// "unctions

, There are following two functions which can be used for binary
: input and output
_ ( * , _ _ _ , si$e t fread void ptr si$e t si$e of elements
_ _ _ , * _ ); si$e t number of elements F&'( a le

_ ( * , _ _ _ , si$e t fwrite const void ptr si$e t si$e of elements
_ _ _ , * _ ); si$e t number of elements F&'( a le

*oth of these functions should be used to read or write blocks of


- . memories usually arrays or structures

!mportant note6

To 1rite in file from -ariables in t3e programe


;ust make t3e follo1ing:
fprintf%File* fp#"Xs"+"Xd"#-ariable&'
fgets%c3ar *string# int lengt3# F,>E * stream&'
c3ar sQ5?R'
fgets% s# 5?# stdin &'

,nstead of using gets)



Lesson 18
PBEPBLCESSLBS

Concept

T 3e C Preprocessor is not part of t3e compiler# but is a


separate step in t3e compilation process)

C Preprocessor is ;ust a text substitution tool and t3ey


instruct compiler to do reDuired preprocessing before
actual compilation)

.ll preprocessor commands beg in 1it3 a pound symbol


%F&)

,t must be t3e first nonblank c3aracter# and for readability

a preprocessor directi-e s3ould beg in in first column)



e+inition

>inclu&e

Finclude Ustandard+library+file+nameV
.ny standard library 3eader file name can appear bet1een
t3e angled brackets)

Finclude Amyfile)3A
13ereas t3e double Duotes form 1ill searc3 t3e current
source directory first# and t3en searc3 t3e default 3eader
file directory if t3e file 1as not in t3e current directory)

Static "unctions

By default all t3e functions in a source file are implicitly


extern# 13ic3 means t3ey are -isible in all ob;ect files 13en
t3ey are processed by t3e linker)

@ou can ensure t3at a function is only -isible 1it3in t3e


source file in 13ic3 you define it by declaring it as static)
static double a-erage%double x# double y& return %x P y& H
7)?' ('

>&e+ine
Fdefine I.C+.BB.@+>E=JTE 7?
T3is directi-e tells t3e CPP to replace instances of
I.C+.BB.@+>E=JTE 1it3 7?) :se Fdefine for constants
to increase readability)

Substitutions 1ill occur and t3is is problem because


no difference bet1een int and float)

2acros

. macro is anot3er preprocessor capability t3at is based


on t3e ideas implicit in t3e Fdefine directi-e examples
youY-e seen so far# but it pro-ides greater flexibility by
allo1ing 13at mig3t be called multiple parameteri0ed
substitutions)
Fdefine macro+name% list+of+identifiers &substitution+string

Fdefine Print%Iy+-ar& printf%AXdA# Iy+-ar&


Iy+-ar is a parameter name# for 13ic3 you can specify a string)
T3is directi-e pro-ides for t1o le-els of substitution)

2acros
Print%i-al&'
T3is 1ill be con-erted during preprocessing to t3is
statement:
printf%AXdA# i-al&'

@ou could use t3is directi-e to specify a printf+s%& function


call to output t3e -alue of an integer at -arious points in
your program)

Strings 0s 2acro 0rguments
T3e simplest string substitution is a single6le-el definition suc3
as t3e follo1ing:
Fdefine I@STB AT3is stringA
Suppose you no1 1rite t3e statement:
printf%AXsA# I@STB&'
T3is 1ill be con-erted during preprocessing into t3e statement:
printf%AXsA# AT3is stringA&'

>un&e+

:ndefined for t3e defined statement)


Fdefine F,>E+S,/E 97
Fundef F,>E+S,/E

>i+n&e+
Fifndef IESS.JE
Fdefine IESS.JE A@ou 1is3ZA
Fendif

T3is tells t3e CPP to define IESS.JE only if IESS.JE isn<t already
defined)
Fifdef 4EB:J
H* @our debugging statements 3ere *H
Fendif
T3is tells t3e CPP to do t3e process t3e statements enclosed if 4EB:J is
defined) T3is is useful if you pass t3e 644EB:J flag to gcc compiler at t3e
time of compilation) T3is 1ill define 4EB:J# so you can turn debugging on
and off on t3e fly during compilation)

Pre&e+ine& 2acros

.=S, C defines a number of macros) .lt3oug3 eac3 one is


a-ailable for your use in programming# t3e predefined
macros s3ould not be directly modified)

Preprocessor /perators

Iacro Continuation %$& . macro usually must be contained


on a single line) T3e macro continuation operator is used
to continue a macro t3at is too long for a single line)
Fdefine message+for%a# b& $
printf%Fa A and A Fb A: 2e lo-e youZ$nA&

Preprocessor /perators

Stringi0e %F&
T3e stringi0e or number6sign operator %<F<&# 13en used 1it3in a
macro definition# con-erts a macro parameter into a string constant)
T3is operator may be used only in a macro t3at 3as a specified
argument or parameter list)
Finclude Ustdio)3V
Fdefine message+for%a# b& $
printf%Fa A and A Fb A: 2e lo-e youZ$nA&
int main%-oid&

message+for%Carole# 4ebra&'
return ?'
(

Preprocessor /perators

Token Pasting %FF&


T3e token6pasting operator %FF& 1it3in a macro definition
combines t1o arguments) ,t permits t1o separate tokens in
t3e macro definition to be ;oined into a single token)

T$e &e+ine&?@ /perator

T3e preprocessor defined operator is used in constant


expressions to determine if an identifier is defined using
Fdefine) ,f t3e specified identifier is defined# t3e -alue is
true %non60ero&) ,f t3e symbol is not defined# t3e -alue is
false %0ero&)

Parameterize& 2acros

Lne of t3e po1erful functions of t3e CPP is t3e ability to


simulate functions using parameteri0ed macros)
int sDuare%int x&
return x * x'
(
2e can re1rite abo-e code using a macro as follo1s:
Fdefine sDuare%x& %%x& * %x&&

Lesson 29
Eeader Files

Concept

. 3eader file is a file 1it3 extension )3 13ic3 contains C


function declarations and macro definitions and to be
s3ared bet1een se-eral source files)

T3ere are t1o types of 3eader files: t3e files t3at t3e
programmer 1rites and t3e files t3at come 1it3 your
compiler)

@ou reDuest t3e use of a 3eader file in your program by


including it# 1it3 t3e C preprocessing directi-e Finclude like
you 3a-e seen inclusion of stdio)3 3eader file# 13ic3
comes along 1it3 your compiler)

Concept

,ncluding a 3eader file is eDual to copying t3e content of t3e


3eader file but 1e do not do it because it 1ill be -ery muc3
error6prone and it is not a good idea to copy t3e content of
3eader file in t3e source files# specially if 1e 3a-e multiple
source file comprising our program)

. simple practice in C or CPP programs is t3at 1e keep all


t3e constants# macros# system 1ide global -ariables# and
function prototypes in 3eader files and include t3at 3eader
file 13ere-er it is reDuired)

!nclu&e Syntax

Bot3 user and system 3eader files are included using t3e
preprocessing directi-e Finclude) ,t 3as follo1ing t1o
forms:
Finclude UfileV

T3is form is used for system 3eader files) ,t searc3es for a


file named file in a standard list of system directories) @ou
can perpend directories to t3is list 1it3 t3e 6, option 13ile
compiling your source code)

!nclu&e Syntax

Finclude AfileA
T3is form is used for 3eader files of your o1n program) ,t
searc3es for a file named file in t3e directory containing
t3e current file) @ou can prepend directories to t3is list 1it3
t3e 6, option 13ile compiling your source code)

/nce#/nly <ea&ers

,f a 3eader file 3appens to be included t1ice# t3e compiler


1ill process its contents t1ice and 1ill result an error) T3e
standard 1ay to pre-ent t3is is to enclose t3e entire real
contents of t3e file in a conditional# like t3is:
Fifndef EE.4EB+F,>E
Fdefine EE.4EB+F,>E
t3e entire 3eader file file
Fendif

/nce#/nly <ea&ers

T3is construct is commonly kno1n as a 1rapper Fifndef)


23en t3e 3eader is included again# t3e conditional 1ill be
false# because EE.4EB+F,>E is defined) T3e
preprocessor 1ill skip o-er t3e entire contents of t3e file#
and t3e compiler 1ill not see it t1ice)

Compute& !nclu&es

Sometimes it is necessary to select one of se-eral different 3eader files to


be included into your program)

T3ey mig3t specify configuration parameters to be used on different sorts


of operating systems# for instance)
@ou could do t3is 1it3 a series of conditionals as follo1s:
Fif S@STEI+5
F include Asystem+5)3A
Felif S@STEI+7
F include Asystem+7)3A
Felif S@STEI+8
)))
Fendif

Compute& !nclu&es

But as it gro1s# it becomes tedious# instead t3e


preprocessor offers t3e ability to use a macro for t3e
3eader name) T3is is called a computed include) ,nstead
of 1riting a 3eader name as t3e direct argument of
Finclude# you simply put a macro name t3ere instead:
Fdefine S@STEI+E Asystem+5)3A
)))
Finclude S@STEI+E

Compute& !nclu&es

But as it gro1s# it becomes tedious# instead t3e


preprocessor offers t3e ability to use a macro for t3e
3eader name) T3is is called a computed include) ,nstead
of 1riting a 3eader name as t3e direct argument of
Finclude# you simply put a macro name t3ere instead:
*de"ine S+ST,-(. /s#stem(01h/
111
*include S+ST,-(.

Compute& !nclu&es

S@STEI+E 1ill be expanded# and t3e preprocessor 1ill


look for system+5)3 as if t3e Finclude 3ad been 1ritten t3at
1ay originally) S@STEI+E could be defined by your
Iakefile 1it3 a 64 option)

Lesson 21
Type Casting

Concept

T#pe casting is a 1ay to con-ert a -ariable from one data


type to anot3er data type)

For example2 if you 1ant to store a long -alue into a


simple integer t3en you can type cast long to int)

@ou can con-ert -alues from one type to anot3er explicitly


using t3e cast operator as follo1s:
t#pe(name! expression

,xample

Consider t3e follo1ing example 13ere t3e cast operator


causes t3e di-ision of one integer -ariable by anot3er to
be performed as a floating6point operation:

!nteger Promotion

,nteger promotion is t3e process by 13ic3 -alues of integer


type AsmallerA t3an int or unsigned int are con-erted eit3er
to int or unsigned int)

Lesson 21
Error Eandling

Concept

.s suc3 C programming does not pro-ide direct support


for error 3andling but being a system programming
language# it pro-ides you access at lo1er le-el in t3e form
of return -alues) Iost of t3e C or e-en :nix function calls
return -0 or $3LL in case of any error and sets an error
code errno is set 4hich is global variable and indicates
an error occurred during an# "unction call) @ou can find
-arious error codes defined in 5error1h6 3eader file)

So a C programmer can c3eck t3e returned -alues and


can take appropriate action depending on t3e return -alue)
.s a good practice# de-eloper s3ould set errno to ? at t3e
time of initiali0ation of t3e program) . -alue of ? indicates
t3at t3ere is no error in t3e program)

T$e errnoA perror?@ an& strerror?@

T3e C programming language pro-ides perror! and


strerror! functions 13ic3 can be used to display t3e text
message associated 1it3 errno1

The perror! "unction displays t3e string you pass to it#


follo1ed by a colon# a space# and t3en t3e textual
representation of t3e current errno -alue)

The strerror! "unction# 13ic3 returns a pointer to t3e


textual representation of t3e current errno -alue)

T$e errnoA perror?@ an& strerror?@

Let7s tr# to simulate an error condition and try to open a


file 13ic3 does not exist) Eere ,<m using bot3 t3e functions
to s3o1 t3e usage# but you can use one or more 1ays of
printing your errors) Second important point to note is t3at
you s3ould use stderr file stream to output all t3e errors)

T$e errnoA perror?@ an& strerror?@

Program ,xit Status

,t is a common practice to exit 1it3 a -alue of


EC,T+S:CCESS in case of programming is coming out
after a successful operation) Eere# EC,T+S:CCESS is a
macro and it is defined as ?)

,f you 3a-e an error condition in your program and you are


coming out t3en you s3ould exit 1it3 a status
EC,T+F.,>:BE 13ic3 is defined as 65)

exit%65&'

exit%?&'

Lesson 22
Becursion

Concept

Recursion is t3e process of repeating items in a self6similar 1ay)


Same applies in programming languages as 1ell 13ere if a
programming allo1s you to call a function inside t3e same
function t3at is called recursi-e call of t3e function as follo1s)
-oid recursion%&

recursion%&' H* function calls itself *H


(
int main%&

recursion%&'
(

Concept

T3e C programming language supports recursion# i)e)# a


"unction to call itsel")

But 13ile using recursion# programmers need to be


careful to define an exit condition from t3e function#
ot3er1ise it 1ill go in infinite loop)

Becursi-e function are -ery useful to sol-e many


mat3ematical problems like to calculate factorial of a
number# generating Fibonacci series# etc)

Bum)er "actorial

"i)onacci Series

Lesson 23
Variable .rguments

Concept

Sometimes# you may come across a situation# 13en you


1ant to 3a-e a function#

13ic3 can take -ariable number of arguments# i)e)#


parameters# instead of predefined number of parameters)
T3e C programming language pro-ides a solution for t3is
situation and you are allo1ed to define a function 13ic3
can accept -ariable number o" parameters based on
#our re8uirement1

T3e follo1ing example s3o1s t3e definition of suc3 a


function)

Concept

int func%int# ))) &


)
)
)
(
int main%&

func%5# 7# 8&'
func%5# 7# 8# 9&'
(

Concept

,t s3ould be noted t3at function func%& 3as last argument


as ellipses i)e) t3ree dotes %)))& and t3e one ;ust before
t3e ellipses is al1ays an int 13ic3 1ill represent total
number -ariable arguments passed)

To use suc3 functionality you need to make use of


stdarg)3 3eader file 13ic3 pro-ides functions and macros
to implement t3e functionality of -ariable arguments and
follo1 t3e follo1ing steps:

9e"ine a "unction 4ith last parameter as ellipses


and the one :ust be"ore the ellipses is al4a#s an int
4hich 4ill represent number o" arguments1

Concept

Create a va(list type -ariable in t3e function definition)


T3is type is defined in stdarg1h 3eader file)

:se int parameter and va(start macro to initiali0e t3e


va(list -ariable to an argument list) T3e macro va(start
is defined in stdarg1h 3eader file)

:se va(arg macro and va(list -ariable to access eac3


item in argument list)

:se a macro va(end to clean up t3e memory assigned


to va(list -ariable)

,xample

,xample

23en t3e pre-ious code is compiled and executed# it


produces t3e follo1ing result) ,t s3ould be noted t3at t3e
function a-erage%& 3as been called t1ice and eac3 time
first argument represents t3e total number of -ariable
arguments being passed) Lnly ellipses 1ill be used to
pass -ariable number of arguments)

Average o" ;2 <2 =2 > ? <1>@@@@@

Average o" >2 0@2 0> ? 0@1@@@@@@



Lesson 2'
Iemory Ianagement

Concept

T3is c3apter 1ill explain dynamic memory management in


C) T3e C programming language pro-ides se-eral
functions for memory allocation and management) T3ese
functions can be found in t3e 5stdlib1h6 3eader file)

0llocating 2emory ynamically

23ile doing programming# if you are a1are about t3e si0e


of an array# t3en it is easy and you can define it as an
array)

For example to store a name of any person# it can go max


5?? c3aracters so you can define somet3ing as follo1s:
c3ar nameQ5??R'

But no1 let us consider a situation 13ere you 3a-e no idea


about t3e lengt3 of t3e text you need to store# for example
you 1ant to store a detailed description about a topic)

,xample

23en t3e pre-ious code is compiled and executed# it


produces t3e follo1ing result)
=ame G /ara .li
4escription: /ara ali a 4PS student in class 5?t3

Same program can be 1ritten using calloc%& only t3ing you


need to replace malloc 1it3 calloc as follo1s:

calloc%7??# si0eof%c3ar&&'

So you 3a-e complete control and you can pass any si0e
-alue 13ile allocating memory unlike arrays 13ere once you
defined t3e si0e can not be c3anged)

1esizing an& 1eleasing 2emory

23en your program comes out# operating system


automatically release all t3e memory allocated by your
program but as a good practice 13en you are not in need
of memory anymore t3en you s3ould release t3at memory
by calling t3e function free%&)

.lternati-ely# you can increase or decrease t3e si0e of an


allocated memory block by calling t3e function realloc%&)
>et us c3eck t3e abo-e program once again and make use
of realloc! and "ree! functions:

Lesson 2'
Command >ine .rguments

Concept

,t is possible to pass some -alues from t3e command line


to your C programs 13en t3ey are executed) T3ese -alues
are called command line arguments and many times t3ey
are important for your program specially 13en you 1ant to
control your program from outside instead of 3ard coding
t3ose -alues inside t3e code)

T3e command line arguments are 3andled using main%&


function arguments 13ere argc refers to t3e number o"
arguments passed2 and argvAB is a pointer arra# 4hich
points to each argument passed to the program)

,xample

Concept

,t s3ould be noted t3at argvA@B 3olds t3e name of t3e


program itself and argvA0B is a pointer to t3e first
command line argument supplied# and 'argvAnB is t3e last
argument) ,f no arguments are supplied# argc 1ill be one#
ot3er1ise and if you pass one argument t3en argc is set at
7)

@ou pass all t3e command line arguments separated by a


space# but if argument itself 3as a space t3en you can
pass suc3 arguments by putting t3em inside double Duotes
AA or single Duotes <<

,xample

Li)rary

S-ar putea să vă placă și