C‐Language
WhatisC
Cis a programming languagedevelopedat AT&T’s BellLaboratories ofUSAin 1972. Itwasdesignedandwrittenby a man named DennisRitchie. Inthelate seventiesCbeganto replace the morefamiliarlanguages of that time like PL/I, ALGOL, etc.
TheCCharacterSet
A character denotes aador rinformation.Figure showsthe valid alph
CTokens
alunits areknown as tokens.
CKeywords
Keywords are the words whose meaning has alreadybeen explainedto the C compiler. The keywords cannotbe used as variablenamesbecause if we do so we are trying to assign a new meaning to thekeyword, which is not allowed by thecomputer. Some C compilersallow you to construct variable names that eit would be safer not to mix
u the variablenames and the keresemble the ke
alled ‘Reservedwords’.
Identifier
Identifiersreferto thenames ofvariables, functions and arrays.They are user‐definednamesan consistof a sequenceof letters and digits, withaletterasa first character.Both uppercase anlowercase letters are permitted. Theunderscore character isalso permitted in identifiers.
Constants
Constantsin C refer tofixed values that do not change duringthe executionof a program.
TypesofCConstants
C constants can be divided into two majo
r categories:Prima Constants
IntegerConstants
An integer constant refersto a sequenceof digits, There are threetypesintegers, namely, decimal,octal,andhexadecimal.
DecimalConstant
A decimal integer constant consists of any combination ofdigitsfrom the set 0 through 9.Eg:123, 321etc.Note:Embedded spaces, commas and non‐digit characters arenotpermitted between digits. Eg: (1)15750(2)$1000
OctalConstant
Anoctal integerconstantconsistsofanycombinationofdigitsfromtheset 0through7,withaleading0.Eg:1)0372) 0435
HexadecimalConstant
Asequenceofdigitsprecededby0xor0Xisconsideredashexadecimalinteger.Theymayalsoinclude0‐9andalphabetsA throughF orathroughf. Eg:1) 0X22) 0x9F 3) 0Xbcd
RealConstants
Certain quantities that vary continuously, such as distances, heights etc., are represented by numberscontaining functional parts like 17.548. Such numbers are calledreal (or floatingpoint) constants. g:0.0083, ‐0.75 etc., A real number may also be expressed in exponential or scientific notation. g:215.65maybe writtenas 2.1565e2
SingleCharacterConstants
A single character constant containsasingle character enclosedwithin a pairof singlequotemarks.Eg: ’5’ ‐ ‘X’ ‐ ‘ ‐ ; ‐ ’ ‐ , StringConstants
Astringconstantisasequence ofcharactersenclosedindoublequotes.Thecharactersmaybeletters,numbers, special characters andblank space. Eg:”Hello!”, “1987”, “?….!”
RulesforConstructingIntegerConstants
(a)An integer constantmusthave at least one digit.(b)It must not have a decimal point.
(c)It can beeither positive ornegative.(d)If no signprecedes an integer constant itis assumed tobepositive.(e)No commas or blanks are allowed within an integerconstant.(f)Theallowable rangefor integerconstantsis‐32768to32767.
RulesforConstructingRealConstants
Real constants are often called Floating Point constants. The real constants could be written in twoforms—Fractional form and Exponential form.
Following rules mustbeobservedwhile constructing real constants expressed in fractional form:
(a)A real constantmusthaveatleastone digit.
(b)Itmusthaveadecimalpoint.(c)It couldbe either positive ornegative.(d)Default sign is positive.
(e)Nocommas orblanksareallowed withinareal constant.Ex.:+3
425.34
‐32.726.0
‐48.6
(b)Themes mustbeobservedwhile constructing real constantsexpressedin exponen
tialform:(a)Them
t and theexponential partshould beseparated by alettere.Following rul5792
t may haveapositive ornegativesign.(c)Default signof mantissa part ispositive.
(d)Theexponentmust haveat least onedigit, which mustbea positiveornegativeinteger.Default sign is positive.
(e)Range of real constants expressed in exponential formis‐3.4e38to 3.4e38.
Ex.:+3.2e
4.1e8‐5
‐0.2e+3‐3.2e‐5
RulesforConstructingCharacterConstants
(a)A character constant is a single alphabet, a single digit or a single special symbol enclosedwithin single inverted commas. Both theinverted commas should pointto the left. Forexample,’A’ is avalid character constant whereas‘A’ is not.
(b)The maximum length of a character constantcan be 1 character.Ex.: 'A', ‘I’,‘5’,'='
Variables
Anentitythatmayvaryduringprogramexecutioniscalledavariable.Variablenamesarenamesgivento locationsin memory. These locations can contain integer, real or character constants. In anylanguage,thetypesofvariablesthatitcansupportdependon thetypesofconstantsthatitcanhandle.This is because a particular type of variable can hold only thesame type of constant. For example,aninteger variable can hold only an integer constant, a real variable can hold only a real constant and acharacter variable can holdonly a character constant.
The rules forconstructing different types of constants are different. However, for construc
ting variablenames of all types the same set of rules apply. These rules aregivenbelow. RulesforConstructingVariableNames
1 (a) A variable name is any combination of 1 to 31 alphabets, digits or underscores. Somecompilers allow variable names whoselength could be up to 247 characters. Still, it would be safer to sticktothe rule of31 characters. Do not create unnecessarilylongvariablenames asitadds to your typing effort.
2 (b) The first character inthe variablenamemust bean alphabet or underscore. 3 (c) No commas or blanks are allowed within a variable name. 4 (d) No special symbol other than an underscore (as in gross_sal) canbe used inava
riable name.Ex.: si_int ,m_hra , pop_e_89
Syntaxofdatatypedeclaration
These rules remain same for all the ty
RulesforCProgram
Before webegin with our first C progr am doremember thefollowing rules that areapplicable to all Cprograms:
Each instruction inaCprogram
1 (a) program would comprise o
is written as a separatestatement. Therefore a comple
te C faseries of statements. 2 (b) The statements in a program must appear inthe same order in which wewish th
em to beexecuted; unless ofcourse the logic of the problem demands a deliberate ‘jump’ or transfer of control toa statement1. (c) Blank spaces m, which is out of sequence. 2. aybeinserted between two words to improve the readability of the statement.
However, no blank spaces areallowed withinavariable, constant or keyword. 3 (d) All statements are entered in small case letters.4 (e) C has no specific rules for theposition at which a statementis to be written. Th
at’s why it is often called a free‐form language.
(f)EveryC statement must end witha ;. Thus ; actsas a statement terminator.
CInstructions
Nowthat wehave written afew programsletus look attheinstructions thatwe usedin theseprograms. There are basically threetypes of instructions in C:
1 (a) Type Declaration Instruction2 (b) Arithmetic Instruction
(c)Control Instruction 1 (a) Type declaration instse instructions is givenbelow:
The purpose of eachofthreuction − To declare the typeof variables used in a C progr
am.
2 (b) Arithmetic instruction −To performarithmetic operations between constants and variables.
−To control thesatements inaCo
oa1. 2. User‐defined data types 2. 3. Derived data types3. 4. Empty data set
All c compiler support four fundamental data types, namely integer (int), character (char), floating point (float), and double – precision floating point (double).
Primarry(orfundaamental)daatatypes
Userdefineddatatypes
C supports a feature known as “typedefinition”that allow user to define an identifier that would represent an existing datatyp
e. Theuser ‐ defineddata type identifier can later be used to declare variables. It takes ge
neral form: typedefexisting_data_typeidentifier; For example. typedefintunits;
unitsbatch1,batch2;
Here, units symbolizes int, and batch1 and batch2 are declared as int variable. The main advantage of typedef is that we can create meaningful data type name for increasing the readability of program.
Enumerateddatatype
Another user-defined data type is enumerated data type provided by ‘C’. It is defined as follows:
The “identifier” is a user-defined enumerated data type which can be used to declare variables that can have one of the values enclosed within the braces (known as enumeration constants). An example.
enum day{MON, TUE,…..SUN};enum day week_st, week_end;
week_st=MON; week_end=FRI; if(week_st==TUE)
week_end=SAT;
Thecompilerautomaticallyassignsintegerdigitsbeginningwith0toalltheenumerationconstants.Thatis,theenumerationconstantvalue1isassigned0,value2isassigned1,andsoon.However,theautomaticassignmentscanbeoverriddenbyassigningvaluesexplicitlytotheenumerationconstants.Forexample:
enumday{MON=1,TUE,……….SUN}week_st,week_end;
Heretheconstant‘MON’isassignedthevalueof1.Theremainingconstantsareassignedvaluesthatincreasesuccessivelyby1.Ingivenexampledeclarationofenumeratedvariablescanbecombinedinonestatement.
StorageClasses
Variables in ccan have not only datatypebut also storage classthat provides information about their location and visibility.
Moreover, a variable’s storage class tells us:
1 (b) What will be thriable would bestored.
2 (a) Where the vaeinitialvalueof thevariable, if initial value is not specifically assig
ned.(i.e. the default initial value).
(c)What is the scopeof the variable; i.e. in whichfunctions the value of the variable would beavailable.
(d)What is the life of the variable; i.e. how long would the variable exist.
TherearefourstorageclassesinC:
(a) Automatic storage class (b)Register storage class(c)Static storage class(d)External storage class
AutomaticStorageClass
Thefeatures ofa variabledefined to havean automatic storage class are as under:
DefaultInitial value ‐‐Memory.
Storage An unpredictable value, which is oftencalled a garbage value.
Scope ‐Local to theblock in which the variable is defined.
Life ‐Till the control remains within the block in which the variableis
Defined.
RegisterStorageClass
A value stored in a CPU register can always be accessed faster than the onethat is storedin memory.
Thefeatures ofa variabledefined to be of register storage class are as under:Storage ‐CPU Registers. DefaultInitial value ‐An unpredictable value, which is oftencalled a garbage value.Scope ‐Local to theblock in which the variable is defined. Life ‐Till the control remains within the block in which the variableisDefined.
StaticStorageClassThefeatures ofa variabledefined to havea staticstorage class are as under: StorageDefaultI
nitial value ‐‐Memory.
Zero.Scope ‐Local to theblock in which the variable is defined. Life ‐Valueof thevariable persists between differentfunction call.
ExternalStorageClassThefeatures ofa variablewhose storage class has been defined as external are as follows:
StorageDefaultInitial value ‐‐Memory.
Zero.Scope ‐Global.Life ‐Aslongastheprogram’s execution doesn’t come to anend.
OperatorsinC
C supports a rich set of operators. Operators areused in programs to manipulate dataand variables.They usually formapart ofthemathematical of logical expressions. C operators are classified intoanumber of categories. They include:
1. 1. Arithmetic operators2. 2. Relational operators3. 3. Logical operators 4. 4. Assignment operator5. 5. Increment and decrement operators 6. 6. Conditionaloperators 7. 7. Bitwise operators 8. 8. Special Operators
ArithmeticOperatorsRelationalOperators
Operator MeaningAddition or unary plusSubtraction or u
+ nary minus
‐* MultiplicationDivision
/% Modulo division or remvainder after diision
We oftencomparetwoquantitiesanddepending ontheir relation, to take certain decisions. Thesecomparisonscan be done with thehelpof relational operators.
Operator< MeaningLess thanGrethan> te
<= arttLhqlGreater thanor equal t>= essanor euao == oEqualtoN
!=
ot equal to
LogicalOperators
Thelogical operatorsareused whenwe want totest morethen onecondition and make decisions.
Logical NOT
AssignmentOperator
Assignment operators areused toassign theresult of anexpression toavariable. Wehave seentheusual assignmentoperator, ‘=’. Inaddition, C has aset of‘shorthand’ assignmentoperators.
=,+=, =,*=,/=,%=
IncrementandDecrementOperators
++,For Ex. ++a or a++;Theoperator++adds 1tot
heoperandwhile – subtracts 1. Botharetheunary operators.
ConditionalOperators
Theternaryoperatorpair ‘?:’ isavailable inC toconstruct conditional expressions of the form
exp1?exp2:exp3;whereexp1,exp2, andexp3 are expressions. The operator
?: work as follows: exp1 is evaluatedfirs. If itistrue, then the expressionexp2 is evaluatedandbecomes the value of the expression. Ifexp1 is false,exp3 is evaluated.
BitwiseOperators
Thespecial operators known asbitwiseoperators for manipulation ofdataatbit level. These operatorsare used fortestingthebits, or shiftingthem rightor left.
Operator&&|| Meaningal ANDlOR
! a
Operator&| Bitwise ANDBitwise OR
Meaning
^ BitwiseXORShift lef
<<>> tShift right
~ ement
One’s complSpecialOperatorsC support some special operat
ors ofinterest suchas comma operator(,),sizeof() operator, pointe
roperators (&and*) and member selection operators (.and>). OperatorPrecedenceandAssociativity
Each operator in C hasa precedence associated with it. This precedenceisused to determinehowanexpressioninvolvingmore than oneoperatoris evaluated. There are distinctlevelsofprecedence andan operator maybelongto one ofthelevels. Theoperatorsat the higher level of precedence areevaluated first. The operators ofthe same precedence areevaluated eitherfrom left toright orfromright to left, depending on thelevel. This is knownas theassociativity property of an operator.
Operator DescriptionFunctioncall Associativity Rank
()[]‐> and .+ Array element referenceStructure operators
Leftto Right 1
‐++!~*&sizeof(t
ype)*
Unary plusUnary minusIncrementDecrementLogical negationOne’s complementPointer reference (indirection)AddressSize of an objectType cast (conversion)
Right to left 2
/%+ MultiplicationDivisionModulusAddition
Leftto RightLeftto Ri 34
‐<<SubtractionLeftshift tLeftto Righgh
5>>< Less thanRight shift tLeftto Ri
6<=>>=== Lessthanor equaltoGreater thanGr
eater than or equal to ghtLeftto Ri
7!=& yBitwise ANDEqualitInequalityB
itwise XOR tLeftto RihghLeftto Ri
h 8^ t 9
| Bitwise ORl AND tLeftto Ri hLefttoRigh 11&&|| t 012
al ORCondition expression tLeftto RighRight toleft
11
?: a t 3= 14
*=/=%=+=‐=&=^=|=<<=>>=
Assignment operators
Right to left Leftto Ri 15, t
Comma operator
ghConsoleI/OFunctions
The screen and keyboard together arecalled a console. Console I/O functions can be further classifiedinto twocategories—formatted and unformatted console I/O functions. The basic differencebetweenthem is that the formatted functions allow the input read from the keyboard or the output displayedontheVDUto beformattedas per our requirements. For example,if valuesofaverage marks andpercentage marks are tobe displayed on the screen, then the detailslike where thisoutput wouldappear on the screen, how manyspaces would be present between the two values, the number ofplaces after the decimal points, etc.canbe controlledusingformatted functions. The functionsavailableunder eachof th
There is n or g npso ans done using standar libraryfunctions.TheformattedconsoleI/Ofunctionscanforcetheusertoreceivetheinputinafixeformat and display the outputin a fixed format. Unformattedconsole I/O functions work faster sincethey donothavetheoverheads offormattingthe input oroutput.
Thereare severalformatsuencesavailabletoformatintand outut.
EscapeSequences
We saw earlier how thenewline character,\n,when insertedina printf( )’s format string, takes thecursor to the beginning of thenext line. The newline character isan ‘escape sequence’,so calledbecause the backslash mbol is considered asan ‘e’ character—it causes anormal interretation of asso that the next characteris as one h
afrom the
ControlStatements
Control Constructs specify the order in which thevarious instructions in a program aretobeexecutedby theComputer. Thereare 4types of control statement in C. They are:
2.Decisio
nnce Control Statements.
1.SequeControl Statements or Conditional Statements.
3.The conditional operators 1. 4. Casecontrol statements.2. 5. Repetitionor Loop Control Statements.
SequenceControlStatements
This type of statements insured thatthe instruction in a programisexecutedin the sameorder.Inwhich they appear in the program. Examples of sequence controlstructure statements are, theprogram will have statements that are placed sequentially and there is no decision involved in theprocess. Also, the program does not require a specific task to be repeatedoverand over again.
DecisionControlStatementsorConditionalStatements
Decision control statements or Conditional Statements allowthe computer to take decision. And forceto work under givencondition or wecan say itgives the control to the computer for taking the decisions. Examples of selectivecontrol structures statements are: C allows decisions to be made byevaluating a given expression as true or false. Such an expression involves the relational and logical operators. Depending on the outcomeof the decision, programexecution proceeds in one direction or another.The Cstatementthat enables these tests to be madeiscalled theifstatements.
The ifstatements may be implemented in different forms depending on the complexity of conditionsto be tested. They are:
1. 1. Simple if statement2. 2. if . . . else statement3. 3. Nested if . . . else statement4. 4. else if ladder
Page|11
SimpleifStatement
Thesimple ifstatementis usedto specify conditionalexec ution of program statementor a group ofstatements enclosed in braces. Thesyntax is: if (test condition)
{ Statement‐block;
}statement‐x;
When an if statement isencountered, testconditionis evaluated first andif itis true, the statement‐block will beexecuted. If the test condition is false, the statement‐blockwill be skipp
ed and the execution will jump tothe statement‐x. When the test condition is true, both the statement‐block and the statement‐x are executedinsequence.The test conditionis always enclosed within apairofparenthesis.Thestatement‐block maybea single statementor a group of statements.
Table below shows the various expressions thatare used as conditions inside an if statement:
ConditionalExpressionb Meaningb
Fore.g.,Valueofa5
Fore.g.,Valueofb5 ResultT
a ==a !=b a is equal to is nt eual to b
55 33 rueFlTruease
a <b
aoqa is less thanb 53 55 FaselTrueF
l
a >b a is reater than b
55 33 aseTFl
a <=b ga is less than or 33 55 rue
aseTTb 35 33 rue
a >=b equalto a is reater than or b
rueFlT55 35 ase
g rueTFlequalto 3 5 rue
ase
Two or more conditions may be combined in an if statementusing a logical AND operator(&&) oralogical OR operator (||). It can compare any numberof variables in asingle if statement. Table belowshows the various expressions thatare used as conditions inside anif statement:
ConditionalExpression
Meaninga is reater than b
Fore.g.,Valueofa30
Fore.g.,Valueofb20
Fore.g.,Valueofc10 ResultT
((a>b)&& (b>c)) gAND b is greaterthan c a is reater than b
3010 1030 2020 rueFalseFalse
1030 2020 3010 False
((a>b)|| (b>c) gOR b is greaterthan c
3010 1030 2020 rueTTTrue
10 20 30 rueFalse
Note:Thereisonlyonestatementintheifblock,thebracesareoptional.Butifthereismore than on
estatement you must use the braces.
if...elseStatement
Sometimes, we can execute one group of statements if thecondition is true and another group ofstatements if the condition is false, in such a situation, the if . . . else statement canbeused.
Theif . . . else statement isan extension of simple if statement. The syntax is:
if (test condition)
{ true‐block‐statement(s);
}else
{ false‐block‐statement(s);
}statement‐x;
Ifthetestconditionistrue,then thetrue‐block‐statement(s)areexecuted.Ifthetestconditionisfalse,then thefalse‐block‐statement(s) are executed. In either case,either true‐block‐statement(s) or false‐block‐statement(s) will beexecuted, not both.
Nestedif...elseStatement
We can write anentire if...else constructwithin eitherthebody ofan ifstatementor the bodyof anelse statement. This is called nesting of ifs. Thesyntax is:if (test condition 1)
{ if (test condi
{tion 2)
} statement‐1;
else
else {} statement‐2;
}
{ statement‐3;
}
statement‐x;If thetest condition 1is false, the statement‐3
will be executed. Ifthetest condition1is true, itcontinues toperform thetest condition 2. If t
he test condition 2 it is true, the statement‐1 will be executes. If the test condition 2 is fals
e, the statement‐2 will be executed and then the control istransferredtothe statement‐x.
elseifLadder
Generally, thecase wherethestatementsin the ifpart of anif...elsestatementisanother ifstatementtendsto beconfusingandbest avoided.Howeveran extremely useful construction occurs when the else part of if statement contains another if . . . else statement. This construction is called as an else ifladder or chain. The syntax is:
Page|13
if (test condition 1)
{
} statement‐1;
else if (test condition 2)
{
} statement‐2;
. . .
. . .
. . .else if (test condition n){
else statement‐n;
}
{ default‐statement ;
statement‐x;Each condition }is evaluated in order
and if anycondition istrue, the corresponding statement isexecuted andtheremainder ofthe chain is terminated and the controlistransferred to the statement‐x. The final elsestatementcontaining thedefaultstatementwillbe executedif none ofthepreviousnconditions are not satisfied.
Casecontrolstatements
The controlstatement which allows us to make a decision from the number of choices is called a switch, or more correctly a switch . . . case . . . default, since these three keywords go together to make up the control statement.
Theswitch statement tests the valueofagivenvariable (or expression) against a listof casevaluesand whenamatch isfound, a blockof statements associated with the case is executed. The syntax is : switch (expression)
{ casevalue‐1:
statement‐1;break;
casevalue‐2:statement‐2;break;
. . .
. . .
}default:
default‐statement;
statement‐x;Where the expression isan integer expressionor characters. value‐1, value‐2 are constantsorconstant expression (valuable to an integral constant) and are known ascase labels. Each of thesevalues shouldbe shouldbe uniquewith a switchstatement. statement‐1, statement‐2 are statementlists and may containoneormorestatements. There isno need toputbracesaroundtheseblocks.Thekeyword caseis followed by an integer or acharacter constant. Eachconstant ineach casemustbedifferent from all others and the caselabels end with a colon(:).
When the switchis executed, the value iscomputed for expression, the list of possible constantexpression values determined fromall case statements is searched for a match.If a match isfound,execution continues after the matching case statement and continues until a break statement isencounteredor theend of statement isreached.
P
age|14
eak statemenntatthe enddof eachbloock signal thheend ofapparticular caase and ca
uses anexitfrromThebr
the swiettch statemeent, transferrring the conntrol to the statement‐
ex
ment following the switch.. The defaullt isan optioonal case. IIf a match iis not foundd
and the ddefault state prefiix is found within swittch,executioon continuees at this pooint. Otherwwise, switchhis skipped entirelyannd the contrrol goes tothestatemeent‐x.
Note :AAt the end of every casee, there shouuld be a breeak statemennt. Otherwisse, it will reesult in caussingthe proggram executtion to contiinue intotheenext casewwhenever caase gets exeecuted.
gotoSttatement
Thegoto statementt isajumpp statementt which jummps from oonepoint tooanother ppoint withinn afunctionn. The gotosstatementiss markedbyy labelstateement. Labeel statementt can beuseed anywheree inthe funcction aboveor below thhement.
RepetiitionorLoopControolStatemennts
This typpe of statements helps tthe computeer to executeeagroup ofstatementsrepeatedly..This allowssaset of innstruction toobeperformmed untilaccertain conddition is reacched. Loopsare dividedinto twocategories pre‐condditional (Entt ry ControlLoops) andpost‐condittional (ExitCControl Loop).
A loopinng process, iiwould includde the followwingfoursteeps:1.Setting andn general,
init
ializatiow
on of counter.2.Test for asppecific condition for exeecution ofthhe loop.3.of the statemments in theloop.
4. Execution
Incrementionng/Decremeentingthecoounter.
Note: The test condition specified in the whileloop should eventually become false atone point of theprogram, otherwise theloop will becomeaninfinite loop.
forStatement
The forloop is entry controlled loop that provides a more concise loop control structure. The syntax is:
Syntax:for (variable initialize; check condition; modify counter)
{ statements 1;
st
atements n;
Explanation: }
1.Theinitializationis usuallyanassignmentthatis used tosetthe loop control variable.2.Thecondition isarelationalexpression that determines when the loop will exit.3.The modify counterdefines how loop control variables will changeeachtime the loopis repeated.
Thesethreesections areseparatedbysemicolon (;). Theforloopis executedas longas the conditionistrue. When, the condition becomes false the program execution will resume on the statementfollowing the block.
Advantage offor loopover otherloops is that, all three partsof for loop (i.e. counter initialization,check condition, modification ofcounter)areimplementedonasingle line.
Thefollowingfigurewould help in fur ther clarifying the conceptof execution of the for loop.
whileStatement
It is an entry controlled loop statement, since the test conditionis testedbefore the start oftheloopexecution. This loops statement is used when the
number of passes are not known inadvance. Thesyntax is:
while(test condition){} bodyofth
eloop;
statement‐x;
dowhilestatement
Thereis aminordifferencebetweentheworking ofwhile anddo ...whileloops.This differenceis theplace where the condition is tested. The while test condition before executing any ofthe statementswithinthewhileloop.Thedo...whileteststheconditionafter havingexecutedthestatements withintheloop.This means thatdo . .. whilewould execute its statements atleastonce, evenif the condition
Page|16
failsforthefirsttimeitself.Thewhile, ontheotherhandwillnotexecuteits statementiftheconditionfails for the first time.
do...whileisanexitcontrolledloopstatement,sincethetestconditionis performed attheendoft ebody oftheloop and therefore the bodyof the loopi s executed unconditionally for the first time. T esyntax is: do
{ bodyof the
loop;
}while (testcondition);
statement‐x;
Where the body of the loop may have one or more statements. On reaching the dostatement, theprogramproceedstoevaluatethebodyoftheloopfirst.Attheendoftheloop,thetestconditioninthewhile statement is evaluated. If the condition is true, then the program continuesto evaluate the bodyof the loop once again. This process continues as long as the condition istrue. When the conditionbecomesfalse, the loop willbe terminated and the controlgoesto the statement‐x thatappearsimmediatelyafterthewhile statement.
Functions
A function isaself‐contained block ofstatements that performs a specified task. The specified task isrepeated each time that the program calls the function. Functions break large computing tasks intosmaller ones. They work together toaccomplish the goalof thewhole program. Every program must containone function named main() where the program always begin execution.
Cfunctionscanbeclassifiedintotwocategoriesnamely:
1. 1. Library functions 2. 2. User‐defined functions
main() is an example of user‐defined function. printf() and scanf() are the examples of libraryfunctions. Other library functions are sqrt, cos, strcat, etc. The main difference between thesecategories isthat library functions are not requiredto bewritten by the user (i.e. they are alreadydefined), whereas a user‐defined functions has to bedeveloped by theuserat the timeof writingaprogram. However, a user‐defined function can later become a part of the C program library.
Some typeof operationor calculation isrepeatedatmany timesthroughout a program. For example,we might use thefactorial ofanumber atseveralpoints inthe program,in suchsituations wemayrepeat the program statements wherever they are needed. Anotherapproach is to design a functionthat canbe called and used whenever required;this saves both time and space.
Afunctioniscalledbysimply using thefunction name inastatement. Generally afunction will processinformationthat ispassedto itfrom the calling partof the program. Information is passed to thefunctionviaspecial identifiers called arguments orparametersand returned via t
he return statement.The functionin which the functioncall is contained is known ascalling function and the function named in the call is said to be the called function.
Thefollowingaretheadvantagesoffunctions:
1. 1. The length of a source program can be reduced using functions at appropriate places. 2. 2. It is easy to locateand isolate a faulty function. 3. 3. A function may be used bymany other programs.
FunctionPrototype
Any C function returns n integer value bydefault. Whenever acallis madeto a function, the compilerassumes that this functionwould returnavalue of type int. Ifwedesirethatafunction should returnavalue other than an int, then it is necessary to mention the calling function in the called function, whichis called as the functionprototype.
Function prototype are usually written at the beginning of the program explicitly before all user defined functions including themain() function. The syntax is:
return_typefunction_name(dt1arg1,dt2arg2,...dtnargn);Wherereturn_typerepresentsthedatatypeofthe valuethatisreturnedby thefunction anddt1,dt2,. . . dtn represents the data type of the arguments arg1, arg2, . . . argn. The datatypesof theactualargumentsmust confirmtothedatatypes of the argumentswiththe prototype. For example:
longfact(longnum);
Here fact is the name of the function,long before the function name fact indicates that the functionreturnsavalueoftypelong.numinsidetheparenthesisistheparameterpassedtothecalledfunction.long before the num indicates that itis of typelong.
Functiondefinition
A function definitionintroduces a new functionby declaringthe typeofvalue it returns, its parametersand specifying thestatements thatare executedwhen thefunction is called. Thesyntax of thefunctiondefinitionis:
return_type function_name(argument_list)
{ local_variable_declarations;
statem 1;statem 2;. . . . . .statement_n;
} return(expression);
Wherethereturn_type specifiesthedatatypeofthevalue to be returnedbythe function. Thedatatypeis assumedto beof type intby default if it is not specified. The return statement is the mechanism forreturning a value to the calling function. This is also an optional statement. Its absence indicates thatno value is being returned to the calling function.
The function_name isused toidentify the function. The rulesfor namingafunction are same as thevariable names.
The argument_list and its associated argument_delclarations parts are optional. The argumentlistcontains valid variablenamesseparatedby comma and the listmust be surrounded by parenthesis.Semicolons are not allowed after the closing parenthesis. The argument variables receive values fromthe calling function, thus providing a means for data communication fromthe calling function tothecalled function. All argument variables must be declared for their types beforetheopeningbraceof thefunctionbody.
The declaration oflocalvariables isrequired only when any local variables are used in the function.Afunctioncan have any number of executable statements.
returnStatement
Afunctionmayormaynotsend backanyvaluetothecallingfunction.Itisdoes,itisdonethroughthereturn statement. The return statement is used to return the information from thefunction to thecalling portionof the program.It alsocauses the program logically to return to the point from wherethe function is accesses (called). The return statement can take one of the following syntax :
return; orreturn ); orreturnconstant); orreturnvariable); orreturnexpression); orreturnconditional_expression);
Page|19
The first and second return statement does not return any value. It acts much as the closing braceofthe function. When areturn is encountered, the control is immediately passed back to the callingfunction. Forexample:
if (choice == ‘n’)return;
The third return statement returnsa constant to the callingfunction. Forexample :if(fact==0)return(1);
Will returns a constant value when the condition specified inside the ifstatementis true. The fourthreturn statementreturnsa variable to the c
alling function. Forexample :if(a>17return(a
;Will returns a variable(which may return any value) to the calling function depending upon the valueof thevariable a. The fifth return statement returns a value depending upon the result of theexpressionspecified inside the parenthesis. For example :return(b*b*‐4*a*c)
Will returns a valuedependinguponthevaluesofa,bandc.Thelast returnstatement returnsavaluedepending upon the result of theconditional expression specified inside the parenthesis. For example :return(a>b?a:b);
Will returns a value dependingupon the valuesofa and b.
Thefollowingaretheimportant points to be noted while using returnstatement :
1. 1. The limitation of a return statement is that of can return only one value from the calledfunction to the callingfunction atatime.
2. 2. The return statementneed notalwaysbepresent at the end of the called function.3. 3. Number of return statements used
in a function is not restricted, since the first returnstatement will return the valuefrom the called function to thecalling function.
4. 4. If thecalled function does not return any value, then the keywordvoid mustbe usedas a datatype specifier.
5. 5. Parenthesis used around the expression ina return statement isoptional.
TypesofFunction
Afunction,dependinguponwhethertheargumentsarepresentor not andwhetheravalueis returnedor not, may be classified as:
1. 1. h noargumentsand no return values.2. 2. but no returnvalues.3. 3. and return values.
Functionwithargumentsbutnoreturnvalues
When afunction has argument, it receives datafrom the callingfunction. The main() function will nothave an control overthewathefunctions receive inut data.We can also make callfunction toread data from the terminal and hecalled function.
Functionwithargumentsandreturnvalues
When afunction has arguments and return values, it receivesdata from the calling function
and doessome processand then returns the result to the called function.In thisway, the main()function willhave controlover the function. Thisapproach seems betterbecausethecallingfunction can check thevalidityofdatabeforeitpassedtothecallingfunctionandtocheck the validityoftheresultbeforeitissenttothestandardoutputdevice(i.e.screen).Whenafunctioniscalled,acopyofthevaluesofactualargumentsis passed to the called function.
Figbelow illustrates theuse of two‐way data communication betweenthe callingandcalled functions.
Recursion
In Cit is possible for the functions to cal itself. Recursion is a processby which a functioncalls itselfrepeatedly until some specified condition has been satisfied. Afunction is called recursive if astatementwithin the bodyof a functioncalls the samefunction, sometimes called circular definition.Recursion is the process of defining something in terms of itself. For example:
mai
n()‐‐
‐‐‐‐‐‐‐‐‐;{
main();
} ‐‐‐‐‐‐‐‐‐‐‐;
Pointers
Pointeris avariablethat holds a memoryaddress, usually thelocation of another variable in memory. ThepointersareoneofC’smostuseful and strongest features. Letibeanordinaryvariablethatstoresthevalueofaninteger.Ifpis anothervariableusedtostore theaddressofvariablei, thenpis calledapointervariable,pointing toi. A pointer mustbe precededbyan asterisk (*), while defin
ing it, so thatitisdistinctfrom othervariables.Thedefinition of apointervariable mustalsospecifythetypeofdatastored in the target variable pointedto it. In our example, thetarget variableis i,is holding integertype data, andhence, thepointer variable pmust be defined as ofthetypeint.
Here,iis the nameofa variablethatstoresthevalue10 andis storedin memoryin theaddress, say1234. This coresented as follows:
Nowconsider anothervariable,p, which holds the addressof thevariable i.Thenp issaid tobe a
Thereare number of adva
1. 1. Pointers incre2. 2. Pointers reduce thelen
a. 3.b. 4.
5. The use of a pointer saving of data storage space inmemory.
DeclaringPointers
syntaxis:
Where data_typeisthetype of iable)whichmayofanyvalidtype.*hiescalled as theivariable is
notan ordinaryvae Pointer_Variable is the name of the For example : int*ptr;
yvariables.
Will declare the variable ptr as a pointer variablethat points toan integer data type. InitializingPointers
It is always good practice to initialize pointers as soon as itisdeclared.Since a pointer isjust anaddress, ifitisnot initialized,it may randomlypointto some location in memory. The ampersand (&)symbol, alsocalled address operator, is applied to avariable to refer the addressof thatvariable.Initializingpointers can bemade topoint toavariable usingan assignmentst
atement. The syntax is: ptr_variable = &variable ;
Here, the address of the variable isassigned toptr_variableas its value. For example:
ptr = &price ;Will cause ptr to pointto price i.e., ptr now contain theaddress of price. A pointer variable can beinitialized in its declarationitself. For example:
Is also valid. i
nt price, *ptr = &price ;
AccessingaVariablethroughItsPointerAccessing the value ofthevariable using pointer isdone byusing unary operator *(asterisk), usuallyknown as indirection operator. Consider the following statements:
int price, *ptr, n ;price = 100 ;ptr = &price ;n=*ptr ;
The first linedeclares the price and n as integer variables andptras a pointer variablepointing toaninteger.Thesecondlineassignsthevalue100topriceandthirdlineassignstheaddressofpricetothepointer variable ptr. The fourth line contains theindirection operator *.W en theoperator*is placedbefore a pointer variable in an expression (on the right hand side of t e equal sign), the pointerreturns thevalueofthevariableof which the pointer value is theaddress.In this case, *ptr returns the value of the variable price, because ptr is the address of price. The * canbe remembered as valueat address. Thus thevalue ofnwouldbe 100.
Array
An array isagroupof related dataitems thatshareacommonname. Arraysare thecontiguousmemory location used to store similardata type or in other terms we can say Arraysare adatastructure which holds multiple variables ofthesamedata type.
OneDimensionalArray
An array with a singlesubscript is known asonedimensionalarray. Consider thecasewhereaprogrammerneeds to keep track ofanumber ofpeople withinan organization. So far, ourinitialattempt will be to create a specific variable for eachuser.This mi ghtlook like:
me2=2;
me1=101;
me3= 1;It becomes increasinglyArrays offerasolution totusing arrays looks like:
int num[5]; num 0 =101 num1 = 32num
num2 = 313 =0;
We created an array called num, whichhas spacefor five integer variables. You mayalsoseethatwestored 0 in the last spaceof thearray. This isacommon technique used byC programmers to signifythe end of an array.
DeclaringArray
Arrays aredefined in thesamemanner as ordinaryvariables, except that each array namemust beaccompanied by the size specification.Thegeneral form ofarray declaration is:
data_typearray_name[size];
data‐type specifies the type ofarray, size is a positive integer number or symbolic constant th
atindicates themaximumnumber ofelements thatcanbe storedinthe array.
Example:floatheight[50];This declaration declaresan array named heightcontaini
ng 50 elements of type float.
Arrayinitialization
TheElementsofarrayare initialized inthesamewayas theordinary variables.E
xample: intnum[6]={2,4,5,35,12,12,67};
TwoDimensionalArray
Two dimensional array (2‐D array)is also called Matrix. General form of 2‐D array is:
data_typearray_name[row_size][column_size];Example: intmarks[4]
[2];DifferentwaysofInitializationofa2DimensionalArray
inttable[2]
[3]={0,0,0,1,1,1};initializationdoneb
yrow
inttable[2][3]={{0,0,0},{1,1,1}};
surrounding the elementsof eachrowby braces.
inttable[2][3]={{0,0,0,},{1,1,1}};
initialization as matrix. MultiDimensionalArray
Arrays of three or more dimension are called Multi‐
DimensionalArray. GeneralformMulti‐DimensionalArray:
data_typearray_name[s1][s2][s3]......[sn];
Example: intsurvey[3][5][12]
Here surveyis a 3‐dimensionalarray declared to contain 180 integer_typeelements. (3x5x12=180)
Initializationof4DimensionalArray
staticintarr[3][4][2]={{{2,4},{7,3},(3,4},{5,1},},{{3,4},{3,4},{3,2},{4,5}},{{2,3},{2,7},{2,3},{4,3}}}
In this example, the outer arrayhas three element , each of which is a twodimensionalarray offourrows, each other of which is a one dimensionalarray of two elements.
String
A string isan array of characters. Strings in Care representedby arrays of characters. The end ofthestring is marked with a special character, the null character (‘\0’), which is simply the character with the value 0.Because C has no built‐in facilities for manipulating entire arrays (copying them, comparing them, etc.), it alsohas very fewbuilt‐in facilities for manipulating strings.
The operations thatare performed on character strings are:
1.Readingand writing strings.2. Combining
3.Copyin strings together.
4.Compgone string to another.
aring strings forequality.
5.Extracting a portion of a string.
DecraringandInitializingStringVariables
A stringvariable is anyvalid Cvariable nameandis always declared as an array. The general form of declaration of a string variable is:char name[30];
Therefore, the sizeshould be equal to the maximum number of characters in the string plus one. Eg: char city[7]= “DELHI”; or charcity[7]={‘D’,‘E’,‘L’,‘H‘,‘I’,‘\0’};
ReadingWords
The familiar input function scanf() canbe used with %s formatspecification to read in a string of characters.
ReadingaLineofText
It is notpossible to use scanf()function to read a line containingmore thanone word. Thisis becausethe scanf()terminates readingassoonasaspaceisencounteredintheinput.Wecan usethegetchar()functionrepeatedly toread single character from the terminal, using thefunctiongetchar(). Thusanentire line of textcan beread and stored in an array. WritingStringToScreen
We have used extensively the printf() function with %sformat toprintstringsto the screen.Theformat %s can be used to display an array of characters that isterminated by the null character. Forexampleprintf(“%s”, name); can be used to display the entirecontents of the array name.
ArithmeticOperationsonCharacters
Callows usto manipulatecharacters the samewaywe dowith numbers. Whenever a characterconstantorcharacter variable isusedin an expression, itis automaticallyconvertedintointeger valueby the system. Eg: if themachine usesthe ASCII representation, then,
x= ‘a’;printf(“%d \n”,x);
will display the number 97 on the screen.
hat converts a strf
PuttingStringTogether
Just as we cannot assign one string to another directly, we cannot join two strings together by thesimple arithmetic addition. That is, the statementssuch as
string3 = string1 + string2;string2 = string1 + “hello”; are not valid. The characters from string1 and string2 should
be copied into string3 one after theother. The process of combining two strings together is calledconcatenation.
Outoftheabovelistweshalldiscussthefunctionsstrlen(),strcpy(),strcat()andstrcmp(),sincethesearethemostcommonlyusedfunctions.
strcat()
The strcat() function joins two strings together.This functionconcatenates the source stringat theend ofthetarget string.
For example, “Bombay”and “Nagpur” onconcatenation would result into astring “Bombay
Nagpur”. strcat(Target_string, Source_string);
strcmp()
This is a function which comparestwostrings to find out whether they are sameor different. Thetwostrings are compared character by character until there is amismatch orend of one of the strings isreached, whichever occurs first.If the two strings are identical,strcmp( ) returns a value zero. Ifthey’re not, itreturns the numeric difference between theASCII values of the first non‐matching pairsof characters.
1) strcmp(name1,name2);2) strcmp(na
me1,”john”;Returns value:
3) strcmp(“r
am”, “rom”);< 0 < Strin==0 == Streing2> 0 > Strin
strcpy()
This functioncopies the contents ofone stringinto another.The base addresses of the source andtargetstrings should besupplied to this function.
strcpy(Target_string, Source_string);
strlen()
This function countsandreturns thenumber ofcharacters inastring.
Len=strlen(string);
PointerArithmetic
Like other variables,pointervariablescanbe usedin expressions. For example, if p1 and p2areproperly declared and initialized pointers, then the followingstatementsarevalid.
y =*p1**p2; sameas(*p1)*(*p2)sum = sum+*p1
z =5*‐*p2/ *p1; sameas(5 * (‐(*p2)))/(*p1)*p2= *p2+10;Note that there is ablankspace between /and*inthe it
em3above. The following iswrong:z =5*‐*p2/*p1;Thesymbol/*consideredasthe beginningofacommentandthereforethestatementfails.Callowsusto add ntegers to or subtract integers from pointers, as well as to subtract one pointer from another.p1+4, p2 –2 and p1– p2 aerallowed.
A word of caution! Donot attempt the following operations on pointers... they would never work out.
(a)Addition of twopointers(b)Multiplication of a pointer with a constant(c)Division of a pointer with a constant
an array d eecaaa bbss camouuosorageeo
all the eledmements of
ndethe array in contiguo ry locations.. The base
address is thelocationnofthe firsttelement (in
x0)ofthhe array. Suppose we dous memor
eeclare an arrayxasfollows:static inntx[5]= {1,22
nd,3,4,5};
Supposee the ba seaaddress of xx is1000 a assuminng that eachhinteger reqquierd twobytes, the ffiveelementts willbe stooredasfolloows:
If we declare p asinteger pointer, then we can makethepoinnter p topooint totheaarray xbythefollowinng assignmeent:
p = x;
This iseequivalent to P = &x[00];
Now, we can accesss everyvaluueofxusinggp+
+tomovve fromoneeelementtooanother. Yoou can also use p ‐‐, p+++ isused too jumpto thhe next memmory locatioon, where p‐‐is used tto jump preevious memorylocationnof array.
InC,a constantchaaracterstrinngalwaysrepresentsappointertothhatstring.Andthereforethe f
ollowwingstatemceents are valid:
char *name;name=n
eDelhi”;
n
a
m
eThese sstatemen
ts will declare as a to characteer and assiggn to namee the c
onsttant
ar
ra
y.
T
T
h
e
st
at
e
m
e
n
nt
li
k
et
his type of asssignm
ent ddoes not appplytocharacctercharacteer string “De
lhi”. You mmightrememmber thatp
oi
nt
er
do notwworkchar
name[20]; name=Delhi”;
Structuure
A structtureis a coonvenient toool for handdling agrouup of logically relatedddata items, we can sayy, Astructurre contains a number oof datatypes grouped ttogether.Thhese
data tyypes may or may not bee ofthe saFor
mmetype.
example,it canbe used to representaa set ofattributes, suchhas studentt _ name, rolll _
number aandmarks. The concenppt of astruccture is anaalogous to thhat of a ‘reccord’ in
maany other languages. Moreexamplees of such sttructures arre:
time: seconnds, minutess, hoursdataa: day,mmonth, year boook: authoor, title, price
cityy: namee, country, poeo
, yearpulation
Page||28
DefiningaStructure
Unlike arrays, structure must be defined first for their format thatmaybe usedlater to declarestructure variables.
The keyword structdeclares a structure to hold the details of four data fields, namelytitle, author,pages, and price.Thesefieldsare called structure elements ormembers. Format of a structuredefinitionis as follows: struct tag_name(Structure_Name)
{ mem 1
mem 2‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐
};
ArrayVSStructure
1) Anarra sa collectionof related data elementsof sametype. Structure can have elements ofdifferenttypes.2) Anarra sderived data typewhereas structure is a programmer‐defined one.
3) Anyarraybehaves likeabuilt‐in data type. All wehaveto do is to declare an arrayvariableand useit. Butin the caseofa structure, first we havetodesign and declare a data structure before thevariablesof that typeare declaredand used.
StructureInitialization
Like primary variables and arrays, structure variables can alsobe initialized where they are declared.Theformatused is quitesimilar tothatused toinitiatearrays.
struct book
{ char name[10] ;
float price;
} ; int pages ;
structbook b1={ "Basic",130.00,550};struct bookb2= {"Physics", 150.80,800 };
Note the following pointswhile declaring a structure type:
a) The closing brace in the structure type declarationmustbefollowed by a semicolon.b)
It is important to understand that astructure type declarationdoes not tell the compiler toreserve any space in memory. All a structure declaration does is, itdefines the ‘form’ of thestructure.
c) Usually structure type declaration appears at the top of the source code file, before anyvariables or functionsaredefined. Invery large programs theyare usually put inaseparateheader file,and the fileis included(using the preprocessordirective #include) in whicheverprogram wewant tousethis structure type.
AccessingStructureElements
Having declared the structure typeand the structure variables,let us see how the elements
of thestructure can be accessed.
In arrays we can access individual elements of an array using a subscript.Structures use a differentscheme.They use a dot (.) operator. Soto refer topagesof the structure defined in our sampleprogram we have to use,
b1.pages
Similarly, to refer toprice we would use,
b1.priceNote thatbeforethhedottheremustalwayysbeastruccturevariablleandafterthedottherremusta
lwwaysbe a strhuucture elemment.
HowSttructurelementsreStored
ver bethe ellementsof aa structure,ttheyarealwways
stored in contiguoous memoryylocations. TTheWhate
followivnngexamplewwouldillusttra
te this:
struuct book
{ char n
ame;float priice ;
ees ;
CopariisionofStrructureVaariables
Two vaariables of the same strructuretype can becoompared thee samewayy asordinarry variabless. Ifperson11and personn2 belong toothesamesstructure, thhen thefollowwing operattions arevallid:
Opeerationngpperson2 Assign personMeani
2 n
2to person11.person2 ‐‐Commpare all meembersofp
erson1 andperson2 annd return 1if thhey areequaal, 0 otherwiise.person1!=person2 ‐Retuurn 1 if all thhe memberssare notequal, 0 otherwwise.
ArrayoofStructurre
We usestructure toodescribethheformatoffa numberoof relatedvaariables. Forrexample, innanalyzingthemarks oobtained byy a classofsstudents, wwe may use aatto describe ame a
nd maarksobtained in variouss subjectsannd then declare all the sstudents aemplate
structu
re variables. Instudent na
such cases, wemaydecclare an arraayofstructuure, eacheleementsofthhearrayreprresentingastructure vaariable.
struuctclassstuudent[100]It definees an array called stuent, that consists;o
f 1000 elements. Each element is defined tobe ofthetype strruct class. Coonsider thefollowing deeclaration:struuct marks
{ ect1 ect2
}; ect3
main()
{stattic struct maarks studentt[3]= {{45,68,81}, {755,53,69}, {557,36,71}
};//This ddeclares thee studentasanarray offthree elemments studennts[0], studeent[1], and student[2] aandinitializes their memmbersas folllows:
stu ct1=45 stuct2=68
……….
stu……
ddent[2].subject3=71;}
An arrayyof structurres is storeddinsidethememory inthe same waayas amulttidimensional array.
Page||30
Union
Like structur es, a union can be declared using thekeywordunion as follows:union item
cessaunion member,we can use the same
all are valid member variables. During accessing, we should makesurethatwe are accessing themember whose value is currently stored. For example, the statement such as:
code.m =379;code.x=7859.36;printf(“%
d”, code.m);would produce erroneousoutput.
MemoryManagement
A memory or storage is required in acomputer to store programs (or information ordata). Datausedby the variables inaprogramis alsoloaded intomemory for fast access. A memoryis madeup ofalarge number of cells, where each cell is capable of storing onebit. The cells maybeorganizedas a setofaddressablewords, each word storingasequenceof bits. Theseaddressablememory cells should be managed effectively to increase its utilization. That is memory managementis tohandle request forstorage (that is new memory allocations for a variable or data)and release of storage (or freeing thememory)in most effectivemanner.
MemoryAllocationinC
There are two typesof memory allocations in C:
1. 1.StaticmemoryallocationorCompiletimememoryallocation.2. 2.DynamicmemoryallocationorRuntimememoryallocation.
StaticorCompileTimeMemoryAllocation
In staticor compile timememoryallocations, the required memory isallocatedto the variablesatthebeginningoftheprogram. Herethememorytobeallocatedisfixed and isdeterminedbyt
he compilerat the compile time itself. For exa
obytes per(total 2) integer variables
int i, j; //Twmple:
floatar [5];//Four bytes per (total5) floating point variables If you try toread 15elements,of anarraywhosesize isdeclaredas 10, thenfirst10values and otherfive consecutive unknown random memory values will be read. Again if you try to assign values to 15elements ofanarraywhose sizeisdeclared as 10,then first 10elementscanbeassignedandtheother5 elements cannotbe assigned / accessed.
The second problem with static memory allocation is that ifyoustoreless number of elements thanthe number ofelements for which youhave declared memory,and thentherestofthememorywillbewasted. That is the unused memory cells are not made available to other applications (or processwhichis running parallelto the program)anditsstatus issetas allocated and not free.This leads to the inefficient use of memory.
DynamicorRunTimeMemoryAllocation
Thedynamicorrun time memory allocation helps us toovercomethis problem.Itmakesefficientuseofmemorybyallocatingtherequiredamountofmemorywheneverisneeded.Inmostofthereal timeproblems,we cannot predict the memoryrequirements.Dynamicmemory allocationdoes the job atrun time.
C provides the following dynamicallocation and de‐allocation functions:
(i)malloc()(ii)calloc()(iii)realloc()(iv)free()
AllocatingaBlockofMemory
The malloc( )function is used to allocate ablock of memory inbytes. The malloc() function returns apointer of any specified data type after allocating a block of memory of specified size. It is of the form
ptr=(int_type*)malloc(block_size)
‘ptr’ isa pointer of any type‘int_type’ byte size is the allocated area of memory block. For example
ptr=(int*)malloc(10*sizeof(int));
On execution ofthis statement,10timesmemory space equivalent tosize of an ‘int’ byte is allocatedand the address of the first byteis assigned tothepointervariable ‘ptr’of type ‘int’.
Remember the malloc() function allocates a block of contiguous bytes. The allocation can failifthespacein theheap(Memory) isnot sufficientto satisfy the request. If it fails, it returns a NULL poin
ter. So itis alwaysbetterto check whether the memoryallocation is successfulor not before we use thenewly allocated memorypointer.
AllocatingMultipleBlocksofMemory
The calloc() function works exactly similar to malloc() functionexcept for thefactthat itneedstwoargumentsas against one argumentrequired bymalloc()function. While malloc() function allocates asingle block of memoryspace, calloc() function allocates multiple blocks of memory, each of the samesize, and then sets all bytes tozero.Thegeneral form ofcalloc() function is
ptr=(int_type*)calloc(n,sizeof(block_size));ptr=(int_type*)malloc(n*(sizeof(block_size));
The abovestatement allocates contiguousspacefor‘n’blocks,eachofsizeofblock_sizebytes. All bytes areinitializedtozeroandapointertothefirstbyteoftheallocated memory blockisreturned.Ifthereisno sufficient memoryspace,aNULL pointer is returned. For example
ptr=(int*)calloc(25,4);ptr=(int*)calloc(25,sizeof(float));
Here, in the first statement the sizeof datatype in byte for which allocation is to bemade(4bytesforafloatingpointnumbers) is specified and 25 specifies the number of elements for which allocation is tobe made.
Note :The memory allocated using malloc() function contains garbage values, the memory allocated by calloc() function contains the valuezero.
ReleasingtheUsedSpace
Dynamic memory allocation allocatesblock(s) of memory when it is required and deallocates or releases when it is not in use. It is important and is our responsibilityto release thememory block forfuture usewhenit isnotin use,usingfree()function. Thefree()function isused todeallocate thepreviouslyallocated memory using malloc() or calloc() function. The syntax of this function is
free(ptr);
ResizetheSizeofaMemoryBlock
In some situations, the previously allocated memory is insufficient to run the correct application, i.e.,we wantto increasethememory space.It isalso possiblethatthe memoryallocated is much larger than necessary, i.e., we want to reducethe memoryspace. In boththecaseswewanttochangethesizeof the allocated memory block andthis can be done by realloc() function. Thisprocessis calledreallocation of the memory. The syntax of this function is
ptr=realloc(ptr,New_Size)
Where ‘ptr’ is a pointer holding thestarting address of theallocated memory block.
And New_Size is thesizein bytes that the system is goingtoreallocate. Following examplewillelaboratethe concept ofreallocationofmemory.
ptr=(int*)malloc(sizeof(int));
ptr=(int*)realloc(ptr,sizeof(int));
ptr=(int*)realloc(ptr,2);/////Boththestatementsaresame
ptr=(int*)realloc(ptr,sizeof(float));
ptr=(int*)realloc(ptr,4);/////////Boththestatementsaresame
FileHandling
Memory isvolatileand its contents would belostoncetheprogramis terminated. Soif weneed thesame dataagainit would haveto beeither entered through thekeyboard again orwouldhave toberegenerated programmatically.Obviouslyboth these operations would betedious. Atsuch times itbecomes necessary to store the datain a manner that can be later retrieved and displayed eitherinpart or in whole. This medium is usually a ‘file’ on the disk.
DataOrganization
Beforewe start doing file input/output let usfirst find out how data is organized on the disk. All data stored onthedisk isin binaryform.Howthis binarydata isstored on the disk varies from one OS toanother.
FileOperations
Thereare different operations that can be carried out on a file. These are:
a) Creationof a new fileb) Opening an existing filec) Reading fromafiled) Writing to a filee) Movingto a specific location in a file (seeking)f) Closing a file
Letus now write a program toread a fileanddisplayitscontents on the screen. We will first list theprogram and show what it does, and then dissect it line by line. Here is the listing…
/* Display contents of a file on screen. */
# include "stdio.h"main()
{ FILE*fp;char ch ;fp = fopen( "PR1.C", "r" );while ( 1 )
{ ch =fgetc (f
F)
if ( ch== EOp ) ;
break;
} printf ( "%c",ch ) ;
} fclose ( fp ) ;
OpeningaFile
Beforewecan read (or write) information from (to)a file on a diskwe mustopenthefile. Toopenthefile we have called the function fopen().It would openafile “PR1.C” in‘read’ mode, which tells theCcompilerthatwe would bereadingthecontents ofthe file. Notethat“r” isastringandnotacharacter;hence the double quotes and not single quotes. In fact fopen()performs three important tasks when you open the file in“r” mode:
a) Firstly it searches on thedisk the file tobeopened.b) Then it loads the file fromthe disk intoa place in memorycalledbuffer. c) It sets upacharacter pointer that point to the first characterof thebuffer.
ReadingfromaFileTo readthefile’s contents from
memory thereexistsafunctioncalled fgetc().This has been usedinour program as,
ch=fgetc(
fp);
fgetc() reads the character fromthecurrent pointer position,advances the pointer position so that itnow pointsto the nextcharacter, and returns the character that is read,which we collected in the variablech. ClosingtheFile
When wehave finishedreadingfrom the file,weneed toclose it. Thisis done using thefunction fclose() through the statement,
fclose(fp);
AFilecopyProgram
This program takes thecontents of afile and copies them into another file, character by character.
#include "stdio.h"main()
{ FILE*fs, *ft;char ch ;fs =fopen ( "pr1.c", "r" ) ; if (fs == NULL )
{ puts ( "Cannot open source file") ;
} exit( );
ft = fopen( "pr2.c", "w" );if (ft== NULL)
{ puts ( "Cannot open target file");
fclose ( fs ) ;
} exit( );
while ( 1 )
{ ch =fgetc (fs ) ;if ( ch== EOF)
else break;
}
fputc ( ch, ft ) ;
fclose ( fs ) ;
} fclose ( ft ) ;
WritingtoaFile
The fputc()function is similar to the putch()function, in the sense that both output characters. However, putch() functionalways writesto the VDU,whereas, fputc()writesto the file. Which file?Thefile signified byft.
FileOpeningModes
In our firstroram ondisk IO wehave oenedthefile inread r” is but one ofthe several modes in which wfile(“r”) mode. However, “
/e can open a
pfile. Following is a list of all possible modes in
which acanbe openped.
gThe tasks performedby
fopen()when a fileis opened in each of these modes are also mentioned.
"r"
Searches file. If the file isopened successfully fopen() loads itinto memoryandsets upapointer which points to the first character in it. If the file cannot be opened fopen() returnsNULL.
Operations possible – reading from thefile.
"w"
Searches file. Ifthefileexists, its contents are overwritten. Ifthefile doesn’t exist,anewfileis created. Returns NULL, if unable to open file.
Operations possible – writing tothe file.
Page|35
“a" Searches file. If the file is opened successfully fopen() loads it into memory and sets up apointer that points to the last character in it. If the file doesn’t exist, a new file is created.Returns NULL, if unable toOperations possible ‐ add open file. ing new contents at theend of file.
"r+" "
Searches file. If is opened successfully fopen() loads it into memory and sets up a pointerwhich points to the first character init.Returns NULL, if unable to open the file. Operations possible ‐reading existing contents, writing new contents, modifying existingcontentsof the file. ’
"w+
Searchesfile.Ifthefileexists,itscontentsareoverwritten.Ifthefiledoesntexistanewfileiscreated. Returns NULL, if unable to open file. Operations possible ‐ writing new contents, reading them back and modifying existingcontentsof the file.
"a+"
Searches file. If the file is opened successfully fopen() loads it into memory and sets up apointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file. Operations possible ‐ reading existing contents, appending new contents to end of file. contents.
Cannot modify existing
String(line)I/OinFiles
Formany purposes, character I/O isjust whatis needed.However, insomesituations the usageoffunctions that read or write entire strings might turn out tobe more efficient.
Readingorwriting strings ofcharacters fromandto files isaseasy as reading and writing individual characters. Here is a program that writes strings to a file using the functionfputs().
/*Receivesstringsfromkeyboardandwritesthemtofile*/
#include "stdio.h"
main()
{ FILE*fp;chars[80];fp = fopen( "POEM.TXT", "w" ) ;if (fp== NULL )
{ puts ( "Cannot open file" ) ;
} exit( );
printf ( "\nEnter afew lines oftext:\n" ) ;while ( strlen (gets (s ))>0)
} fclose ( fp ) ;}{
fputs ( s, fp ) ;
fputs ( "\n", fp ) ;
And here is a sample run of the program... Enter a fewlines of text: Shining and bright, they areforever,so true about diamonds,more so ofmemories,especially yours !
Page|36
Note thateach stringis terminatedby hitting enter.To terminate the execution of theprogram, hit enter at the beginningof a line. This creates astring of zero length, which the program recognizesasthe signal to close the file and exit.
Here is aprogramthat reads strings from a disk file
/*Readsstringsfromthefileanddisplaysthemonscreen*/
#include "stdio.h"
main()
{ FILE*fp;chars[80];fp = fopen( "POEM.TXT", "r" ) ; if (fp== NULL )
{ puts ( "Cannot open file" ) ;
} exit( );
while ( fgets( s,
printf ( "%s", s ) ;79, fp ) != NULL )
} fclose ( fp ) ;
And here is the output...Shining and bright, they areforever,so true about diamonds,more so ofmemories,
The functionespecially yours !
fgets()takesthree arguments.Thefirstisthe address where thestringisstored, and thesecond is the maximum length of thestring. This argumentpreventsfgets( )from reading in too long a string and overflowingthe array.The third argument, as usual, is the pointer to the structure FILE.
RecordI/OinFiles
So far wehave dealt withreadingandwritingonlycharacters and strings. What if wewant to read or write numbers from/to file? Furthermore, what if we desire to read/write a combination of characters, strings and numbers? Forthis first wewould organize this dissimilar data togetherin astructure and then use fprintf() and fscanf()library functions to read/write data from/to file. Following program illustrates the use of structuresfor writingrecords of employees.
/*Writesrecordstoafileusingstructure*/
#include "stdio.h"main(){
FILE{
*fp;
char another= 'Y' ;struct emp
char name[40] ;int age ;
} ; float bs ;
structempe;fp = fopen( "EMPLOYEE.DAT", "w") ;if (fp== NULL )
{ puts ( "Cannot open file" ) ;exit( );
Page|37
}while( another=='Y')
{ printf ( "\nEnter name, ageand basic salary: " ) ;scanf ( "%s %d %f", e.name, &e.age, &e.bs ) ;fprintf (fp, "%s %d %f\n", e.name, e.age, e.bs );printf ( "Add another record (Y/N) " );
} fclose ( fp ) ;} fflush (stdin ) ;
another = getche( ) ;
And here is the outputof the pr
ogram...Entername,age and ba
sicsalary: Sunil 34 1250.50
Entername,age and b
Entername,age and basic salary:Sameer211300.50
Add another record (Y/N) NIn asicsalary: Rahul 34 1400.55
thisprogramwearejustreadingthedataintoastructurevariableusingscanf(),andthendumpingit into a disk file using fprintf().Theuser can input asmany records ashe desires.Theprocedureends whenthe usersupplies ‘N’ forthe question‘Add anotherrecord (Y/N)’.
Someotherfunctions
Function file Syntax Example*FILE infil
fopen‐Open fclose– clos
FILE*fopen(char*filename,char*mode)Filename– stringfilenamewith pathMode –mode ofopeningrwreadonlywrite onlyaappend file+ read and write(r+/w+/a+)Return value–FILEpointer on success NULL onfailure
e ;Infile=fopen(“a.txt”,”r”);FILE *outfile = fopen(“b.txt”,”w”);if(infile==NULL ||outfile==NULL){printf(“error”);}
etheopenfile fgetc– readone char
fclose(FILE*fptr)fptr – FILE*of theopenfileReturns void
fclose(infile);
fromfile fputc – writ intfgetc(FILE*fptr)fptr – FILE*of theopereturns – character rnfileead1oneof orerror
while( (ch=fgetc())!=‐1)putchar(ch);//display content of file//on screen
eonecharacter tothe file int fputc(int ch,FILE *fptr)ch – character to writefptr – openfile pointerreturns character writtenEOF if thereis error
for(ch=’A’;ch<=’Z’;ch++)fputc(ch,fptr);
fscanf–Formattedreadfromfile
intfscanf(FILE*ptr,char*fmt,…)ptr – FILE pointerfmt –formatspecifier forvariables tobe readReturns – numberof values read
fscanf(infile, “%d %d”,&n1,&n2);
successfully fprintf –f
is
write to fileormatted
fread – read from
intfprintf(FILE*ptr,char*fmt,…)ptr – FILE pointerfmt – formatspecifier for variables to be readReturns – number of characters printed or negative number on error
fprintf(outfile,“Value%d\n”,n1);
binary file fwrite – writ to
intfread(void*buffer,size_tsize,size_tnum,FILE*ptr)buffer – stores thevaluereadsize – sizeofthe buffer num – number of blocks to be read ptr – file pointerReturns – number of values read
Char *str = malloc(50);fread(str,50,1,infile); i
eabinary file e thefile intfwrite(void*buffer,size_tsize,size_tnum,FILE*ptr)buffer – stores thevaluereadsize – sizeofthe buffer num – number of blocks to be read ptr – file pointerReturns – number of values written
for(i=0;i<10;++)fwrite(&i,sizeof(i),1,outfile);char a[]=”end”;fwrite(a,strlen(a)+1,1,outfile); E==
fseek – movpointer by given offset et th
intfseek(FILE*ptr,longoffset,intwhence)ptr – file pointeroffset – offsetin bytes from third parameterwhence – SEEK_SET – frombeginningof fileSEEK_CUR – from current positionSEEK_END –fromend of file Returns – zero on success Non‐zero onfailure
if(fseek(infile,4L,SEEK_ST)0){ charch=fgetc(infile);printf(“Thefile is %c\n”,ch); fourth char of the }
ftell –geof file pointer position rewind – moves th
intftell(FILE*ptr)ptr – FILE pointerReturns – position of file pointer‐1 on error
FILE *ptr= fopen(b[1],"r");fseek(ptr,0L,SEEK_END); int size_of_file = ftell(ptr);
efile pointer to the ofthe file
voidrewind(FILE*ptr) rewind(infile);int n = fscanf(infile,”%d”,&n);
beginning
ptr – FILE pointer
BitwiseOperators
One of C’s powerful features is a set of bit manipulation operators. These permit the programmer toaccess and manipulate individual bit
Operator~ Meaning
One’s complementRight shift
>> Leftshift<<& Bitwise AND
Bitwise OR^
|
swithin a piece of data. The variousBitwise Operators availablein Care shown inFigure. Bitwise XOR(Exclusive OR)
Throughoutthisdiscussionof bitwiseoperatorswearegoingto useafunctioncalled showbits().Thetask ofshowbits()is to display thebinary representationofany integerorcharactervalue.
We beginwith a plain‐janeexamplewithshowbits()in action.
/*Printbinaryequivalentofintegersusingshowbits()function*/
main()
{ int j ;for ( j=
{ 0; j<<= 5; j++)
} } printf ( "\nDecimal %dis sameas b
inary ", j );showbits ( j );
And here is the output...
0 meas 01 meas 12 meas 03 meas 1 4 meas 05 meas 1
Letusnowexplorethevariousbitwiseoperatorsonebyone.
One’sComplementOperator
On taking one’s complement of a number, all 1’s present in the number are changed to 0’s and all 0’sare changedto 1’s. For example one’s complement of 1010is 0101. Similarly, one’s complement of1111is 0000.Note thathere when we talkof a numberwe are talking of binary equivalent of thenumber. Thus, one’s complement of 65 means one’s complementof 00000000 01000001, which isbinary equivalentof 65. One’s complementof65thereforewouldbe, 11111111 10111110. One’scomplement operator is
) represented by the symbol ~. Following program shows one’s complementoperat
orin action.main(
{ int j, k ;
for ( j=0; j<=3; j++ )
{ printf ( "\nDecimal %dis sameas binary ", j );showbit
s ( j );k = ~j ;printf ( "\nOne’s c} } showbits ( k
o
mplementof %d is ", j ) ;
);
And here is the output of the above p
rogram...
Decimal0is sameas
0000000000000000
One’scomplementof0is111111111111
1111
Decimal1is sameas
0000000000000001
One’scomplementof1is111111111111
1110
Decimal2is sameas
0000000000000010
One’scomplementof2is111111111111
1101
Decimal3is sameas
0000000000000011
One’scomplementof3is111111111111
1100 In real‐
world situationswhere could theone’s
complementoperator be useful? Sinc
e it changes theoriginal number beyo
ndrecognition, one potential place w
here itcanbe effectively usedis indev
elopment of afileencryption utility as
shownbelow:
/* File encryption utility */
#include "stdio.h"
main()
{
}
encrypt( ) ;
encrypt( )
{
FILE*fs, *ft;
char ch ;
fs =fopen ("SOURCE.C", "r" ) ; /* nor
malfile*/
ft =fopen( "TARGET.C”, "w" ) ; /*
encrypted file*/
if ( fs == NULL || ft == NULL )
{ printf ( "\nFile opening error!" ) ;
P
a
g
e
|
4
1
} exit (1) ;while ( ( ch=getc( fs) )!= EOF)
putc
( ~ch,ft) ;
fclose ( fs ) ;
} fclos
e ( ft ) ;
RightShiftOperator
The right shift operator is represented by >>. Itneeds two operands. Itshifts eachbitin its leftoperandto the right.Thenumberofplaces the bitsareshifted depends onthenumber following theoperator(i.e. its rightoperand).
Thus,ch>>3wouldshiftallbitsinchthreeplacestotheright.Similarly, ch>>5wouldshiftallbits5
places to the if the variable ch containsthebitpattern11010111,then,
ch>>1wouldgive01101011For exampleright.
and ch>>2would give00110101.
Note that asthe bits are shifted tothe right, blanks are created on the left. These blanks must be filledsomehow. They are always filled with zeros. The following program demonstrates the effectof rightshift operator.
main({ )
inti=5225,j,k;
printf ( "\nDecimal %dis sameas binary ", i );
showbits ( i );
for ( j=0; j<=5; j++ )
{ k = i>>j ;printf ( "\n%d right shift %d gives ",i, j ) ;
} } showbits (
k);
The output of the above program would be...
Decimal5225issameas binary0001010001101001
t t0 ve 01010001101001
t t1 ve 1010 110100
t t2 ve 0101 011010
t t3 ve 1010 1101
t t4 ve 0101 0110t t5 ive 0010100011
AWordofCaution
In the explanation a>>b if b isnegative the resultis unpredictable.If ais negative than its left mostbit (sign bit) would be 1. On some computer right shifting a would resultin extendingthe signbit. Forexample, if acontains ‐1,its binary representation would be1111111111111111. Without signextension, theoperationa>>4wouldbe0000111111111111. LeftShiftOperator
This issimilarto the right shift operator, the onlythat thebits are shifted totheleft,andforeachadded to theright of the number. The following clarifymy point.
main()
{ inti=5225,j,k;
printf ( "\nDecimal %dis sameas ", i );
showbits ( i );
for ( j=0; j<=4; j++ )
{ k = i<<j ;printf ( "\n%d left shift%d gives", i, j ) ;
} } showbits ( k);
The output of the above program would be...
Decimal5225issameas binary0001010001101001
ts t0 s 001010001101001
ts t1 s 0101 01101001
ts t2 s 1010 11010010
ts t3 s101 01101001ts t4 s010 11010010
BitwiseANDOperator
This operatoris represented as &.Remember itis different than &&, the logical AND operator. The &operatoroperates on twooperands.Whileoperatinguponthesetwo operands theyarecompared onabit‐by‐bit basis.Henceboth the operandsmust beof the sametype (either char or int). The secondoperandisoftencalledanANDmask. The &operatoroperateson apairof bitstoyield aresultant bit.Therules that decide thevalue oftheresultantbitare shownbelow: Suppose,from the bit pattern10101101of anoperand, wewant tocheck whether bit number 3is ON
(1)or OFF (0).Sincewe wantto check the bit number3, thesecond operand for the AND operationshould be1*23, whichisequalto8. This operandcan be representedbitwiseas00001000.Then theANDing operation would be,
10101101 Original bitpattern
00001000 AND mask
00001000 Resultingbitpattern
BitwiseOROperator
Another important bitwise operator is the OR operator which is represented as |. The rules thatgovern thevalueofthe resulting bitobtained afterORingof twobits is shown in the truth table below.
FirstBit0 SecondBit0 FirstBit|SecondBit001 10 11
1 1 1
Using the Truth table confirm the result obtained onORing thetwo operands as shown below.
11010000 riginal bitpattern00000111 R mask
11010111 Resultingbitparticular bitinanumber.
Bitwise OR operator is usually usedtoput ON apattern
Letus consider the bit pattern11000011. Ifwewantto putONbitnumber 3,then the ORmask tobeusedwould be00001000. Notethat all the other bits in the maskaresetto 0 and onlythebit, whichwe want toset ON in theresultingvalue is setto1.
BitwiseXOROperator
The XOR operator is represented as ^ and isalso calledanExclusive OROperator.TheOR operatorreturns1,whenanyoneofthetwobitsorboththebitsare1,whereasXORreturns1onlyifoneofthetwo bits is 1.
Thetruth table for the XOR operatoris given below.
FirstBit0 SecondBit0 FirstBit^SecondBit001 10 11
1 1 0
XORoperator isused totoggleabitONorOFF.AnumberXORedwithanothernumbertwicegivestheoriginalnumber. This isshown inthefollowing program.
main()
{ int
b=50;b = b
^ 12 ;
n this will print 62}
b = b ^ 12 ;n this will print 50
Preprocessor
It is a program that processes our source program before it is passed to the compiler. Thepreprocessor offers several features called preprocessor directives. Each of these preprocessor directives beginswith a# symbol.The directivescanbe placed anywhereina program but aremostoften placedat the beginning of a program, before the first function definition. We would learn the following preprocessor directives here:(a)Macro expansion
(b)File inclusion(c) Conditional Compilation (d)Miscellaneous directives
MacroExpansion
Have a look at the following program.#define UPPER 25main()
int i ;{
for ( i=1; i<= UPPER ;i
} printf ( "\n%d", i ) ;
++ )
Inthisprograminsteadofwriting25inthe for loopwearewritingitintheformofUPPER,whichhasalready been defined beforemain() through the statement,
#defineUPPER25
This statement is called ‘macro definition’ ormore commonly, just a ‘macro’. What purpose does itserve? During preprocessing, the preprocessor replaces every occurrence of UPPER in the program
with 25. #define PI3.1415 mai
n()
floatr=6.25;{
float area;area = PI * r * r ;
} printf ( "\nArea of circle = %f", area ) ;
When we compile the program, before the source code passes to the compilerit isexamined bytheCpreprocessor for any macro definitions. When it sees the #definedirective, it goes through the entire program in search of the macro templates; wherever it finds one, it replaces the macro template withthe appropriate macro expansion. Only after this procedure has beencompleted is the programhanded over to the compiler.
A#define directive is manya times used to defineoperators as shown below.
#define AND&& #define OR ||main()
{ int f= 1,x=4, y= 90 ;if ( (f<5)AND ( x <= 20OR y <=45))
} else printf ( "\nYour PC will always work fine..." ) ;
printf ( "\n
In front of themaintenance man") ; MacroswithArguments
The macros that we have used so far are called simple macros. Macroscan havearguments, justasfunctionscan. Here is an examplethat illustrates this fact.
#define sum(a,b)(a+b)main()
{ clrscr();
printf(“Sum=%d”,sum(10,20));
} getch();
Here aresome important points to remember while writing macroswitharguments:
a)
Be carefulnot toleaveablankbetween the macro templateandits argument while defining
the macro. For example, there should be no blankbetween sum and (a,b) inthedefi
nition,b) The entiremacro expansion shouldbeenclosed within parentheses.c)
Macroscanbe split intomultiple lines,with a ‘\’ (back slash)presentat the end ofeach li
ne.
Following programshowshow wecan define and use multiple linemacros.#defineVLINE( X, Y ){\
gotoxy( X,
Y) ; \
printf
( "%c
",179
);\
}
MacrosversusFunctions
In amacro call the preprocessor replaces the macro template with itsmacro expansion,ina stupid,unthinking, literal way. As against this, in afunction call the control is passed to afunction along withcertain arguments, somecalculationsareperformedinthefunctionandausefulvalueisreturnedbackfromthefunction.
This brings ustoa question: whenisitbest tousemacroswithargumentsandwhenisitbettertousea function? Usually macros make the program run faster but increase the program size, whereasfunctionsmake the program smaller and compact.
If weuseamacro hundred times inaprogram, the macro expansion goesinto our source codeathundred different places, thus increasing the program size. On the other hand, if afunction is used,theneven ifit is calledfromhundred different places in the program,it would takethesameamountofspacein theprogram.
But passing arguments to a function and getting back the returned value doestake timeandwouldtherefore slow down the program. Thisgets avoided withmacrossince they have already beenexpandedandplaced in the source code before compilation.
Moralof the story is—if the macro issimple and sweet likein our examples it makes nice shorthandandavoids the overheads associated withfunction calls.On the other hand ifwe haveafairly largemacro and it is used fairly often, perhaps we ought to replaceitwith a function.
FileInclusion
The secondpreprocessor directive we’ll explore in this chapter isfile inclusion. Thisdirectivecausesone file to be includedinanother.Thepreprocessor command for file inclusion loo
ks like this:
#include"filename"
anditsimplycauses theentirecontentsoffilenametobeinserted into thesourcecodeatthat pointinthe program.Of course this presumes that the file beingincluded isexisting.When and why thisfeatureis used?Itcanbeusedintwo cases:
a) If we have a very large program, the code is best divided into several different files, eachcontainingaset of related functions. It is agood programmingpractice to keep differentsections of a large program separate. These files are #includedat the beginning of mainprogram file.
b) Therearesomefunctions and somemacro definitions thatwe need almost in all programsthatwewrite.Thesecommonlyneededfunctionsandmacrodefinitionscanbestoredinafile,and that file can be included in every program wewrite, whichwould add all the statementsin this filetoour programas if wehave typed themin.
Actually thereexist twoways towrite #include statement.Theseare: #include"filename"
Them#include<filename>eaning of ea
chofthese forms isgiven below:
#include "goto.c"
This command would look for the file goto.c in the current directory aswellas the specified listof directories asmentionedin the include search paththatmighthavebeensetup.
#include <goto.c>
This command would look for the file goto.c in the specified list ofdirectories only.
ConditionalCompilation
We can,if wewant,have the compilerskip overpart ofasource code by inserting the preprocessingcommands #ifdefand#endif, which havethegeneral form:
#ifdefmacronamestatement1 statement2statement3
#endifIfmacroname has been#defined, the blockofcode will be proc
essed as usual; otherwise not.
Where would #ifdefbe useful? When would youlike tocompile only a part of your program? In threecases:
a)
To“commentout”obsoletelinesofcode.Itoftenhappensthat aprogramischangedatthelastminute tosatisfyaclient. Thisinvolves rewriting somepart of source code to the client’ssatisfactionanddeleting the old code. But veteran programmersare familiar with the clientswho changetheir mind and wanttheold code back againjust the wayitwas.
Now you would definitelynotlike toretype the deleted codeagain. One solution insuch a situation isto put theold codewithinapair of/* */ combination. But wemight have already written a commentinthecode thatweareabout to“comment out”.Thiswouldmean we end upwithnestedcomments.Obviously, this solution won’twork since we can’tnest comments in C.
Therefore the solutionisto useconditional compilation as shown below.
main()
{ #ifdefOKAY
statement1 statement2 /* detects virus */statement3statement4;/* specifictostonevirus*/
#endif statement5 statement6
} statement7
Here, statements 1, 2, 3 and 4 would get compiled only if the macro OKAYhasbeen defined,andwehave purposefully omittedthedefinitionof themacro OKAY. Ata later date, if we want that thesestatements should also get compiled all that weare required to dois todelete the #ifdefand#endifstatements.
b) A more sophisticated use of #ifdefhas todo withmaking the programsportable,i.e. tomakethemworkontwototallydifferentcomputers.Supposeanorganizationhastwodifferenttypesofcomputersandyouareexpectedtowriteaprogramthatworksonboththemachines. Youcandoso by isolating the lines of code that must be different for each machine by marking them off with#ifdef.For example:main()
{ #ifdefINTEL
#else code suitable for a Intel PC
code suitable for a Motor
ola PC
} #endif
code common to boththe computers When you compile this program it woul
d compile only the code suitable for a Intel PCandthecommon code. This is because the macro INTEL has not been defined. Note that the working of #ifdef ‐#else ‐
#endif is similar to theordinary if‐else control instruction of C.
If youwanttorun yourprogramona Motorola PC,just add a statementatthe topsaying,
#defineINTEL
Sometimes, instead of #ifdef the #ifndefdirective is used. The #ifndef(which means ‘if notdefined’) works exactly opposite to #ifdef. The above example if written using #ifndef, wouldlook like this:main()
{ #ifndefINTEL
#else code suitable for a Intel PC
code suitable for a Motor
ola PC
} #endif
code common to boththe computers
c)Supposeafunctionmyfunc()isdefinedinafile‘myfile.h’ whichis#includedinafile‘myfile1.h’.Now in your program fileif you #include both ‘myfile.h’ and‘myfile1.h’ the compilerflashesanerror ‘Multiple declaration for myfunc’. This is because the same file ‘myfile.h’gets includedtwice. Toavoid this we can writefollowing code intheheader file.
#ifand#elifDirectives
The #if directive can beused totest whether anexpressionevaluatesto anonzero value or no
t. If the
result of the expressionis nonzero, then subsequent lines upto a #else, #elif or #endif are compiled,otherwise theyare skipped.A simpleexample of#if directive is shown below:
main()
{ #ifTEST<=5
statement1 statement2statement3
#else statement4
} #endif statement5
Page|48
If the expression, TEST<=5 evaluates totrue thenstatements 1,2and3arecompiled otherwisestatements4, 5 and 6arecompiled.
MiscellaneousDirectives
There are two more preprocessor directives available, though they are not very commonly used. Theyare: (a)#undef
(b)#pragma
#undefDirective
On some occasions it may be desirable to cause a defined name to become ‘undefined’. This can beaccomplished by means of the #undef directive.In order toundefineamacro thathasbeen earlier #defined, the directive,
can b#undefmacrotemplate
eused. Thus the statement,
#undefPENTIUM
would cause the definition ofPENTIUM toberemoved from the system. All subsequent #ifdefPENTIUM statements wouldevaluatetofalse.
#pragmaDirective
This directive is another special‐purpose directive that you can use to turn on or off certain features.Pragmasvary fromonecompiler toanother. There are certain pragmas available with Microsoft Ccompilerthat dealwith formattingsourcelistings and placingcommentsintheobjectfilegeneratedbythecompiler.TurboC/C++compilerhasgotapragmathatallowsyoutosuppresswarningsgeneratedby thecompiler. Someof thesepragmas are discussed below.
a) #pragmastartup and #pragmaexit: These directivesallow us tospecifyfunctions thatarecalled upon program startup (before main())or program exit(justbefore the programterminates). Their usage is as follows:
void fun1(
void fun2(
#pragmastartupfun1
#pragmaexitfun2
main()
{
} printf ( "\nInside maim");
void fun1()
{
} printf ( "\nInside fun1");
void fun2()
{
} printf ( "\nInside fun2");
And hereis the output ofthe program.Inside fun1Inside mainInside fun2
b) #pragmawarn:This directive tells the compiler whether or not we want tosuppress aspecific warning.
Page|49
TypesofProgramErrors
Program errors are also referred to as program bugs.
A C program mayhave one or moreoffour types of errors:
% • Syntax errors (Compiler errors or Compile‐time errors)% • Linker Errors
% • Runtime errors % • Logic errors
Usually, the errors becomemoredifficult tofindand fix as youmovedownthe above list.
Syntaxerrors
Syntax errors represent grammarerrors intheuseof the programming language. Commonexamples are:
% • Misspelled variable and function names% • Missing semicolons % • Unmatchedparentheses, squarebrackets, and curly braces% • Using a variable that has not been declared % • Incorrect format in selection and loop statements
Syntaxerrorsaretheeasiesttofindandfix.Overtheyears,compilerdevelopershave workedhard to make compilers smarter so that they can catch errorsat compile timethat mightotherwise turn out to be runtime errors.
Examples:
1. 1. Simple statement not terminated by semicolon: 2. 2. Using a variable before it is declared:
3.Missing closing parenthesis, ) , in theprintf satatement:
printf(“Enter Any No”;
Linkererrors
Linker errorsare generated when the linkerencounters what looks like a function call; butit cannot find afunction with thatname.This isusually causedby misspelling aCstandard function (like main)or not including theheader file for a function.
Examples:
1. 1. Misspelling a standard Cfunction. 2. 2. Not including the header file for a function.
Runtimeerrors
Atype oferrorthat occurs duringtheexecutionof a program is known as run‐time error. Runtimeerrors maycrash your program when you run it. Runtime errorsoccur when a program with no syntaxerrors directs the computer to execute an illegal operation. Common exam
ples are:
% • Trying to divide by a variable that contains a value of zero % • Tryingtoopena file that does notexist
There is noway for the compiler to know about these kinds of errorswhen the program iscompiled. Runtime errors are commonly due to wronginput from the user. Runtime errorsare usually more difficult to find and fix than syntax errors.
To find the source of a run‐time error in a program, usually software called debugger isused.
Example: Whenthefollowing program isexecuted and the userinputs 0 for num2, a run‐timeerroroccurs due to division by zeroin theexpression num1/num2
Logicerrors
Logic errors occur when aprogrammer implements the algorithm for solving aproblem incorrectly. Astatement with logical error may produce unexpected and wrong resultsin the program. Commonexamplesare:
% • Multiplying when you should be dividing % • Adding when you should be subtracting% • Opening and using datafromthewrongfile % • Displaying the wrong message
Logic errors are the hardest to find and fix because:
% • Thecompilerdoes not detect these errors % • There is no indication of error whenthe programis executed. % • The program may produce correct results for some input data and wrong r
esults for otherinput data.
Logicerrors can onlybe detectedby examining the programthoroughly.This isusually done byusing adebugger.
Debugging
Debugging is a methodical process of findingand reducing the number of bugs, or defects, ina computer program.
or
In computers, debuggingis the process of locating and fixingor bypassing bugs (errors) in computerprogram code.
Debugger
A debugger is a computer programthatlets you run yourprogram, line by line andexamine thevalues ofvariablesor lookat values passed into functions and let you figureoutwhyit isn't runningthe way youexpected it to.