0% found this document useful (0 votes)
25 views77 pages

C Quick Guide

This is very useful for quick revision of c language.

Uploaded by

gsaijanardhan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views77 pages

C Quick Guide

This is very useful for quick revision of c language.

Uploaded by

gsaijanardhan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

11/4/2015

CQuickGuide

CQUICKGUIDE
[Link]

[Link]

CLANGUAGEOVERVIEW
Cisageneralpurpose,[Link]
developtheUNIXoperatingsystematBellLabs.CwasoriginallyfirstimplementedontheDECPDP11
computerin1972.
In1978,BrianKernighanandDennisRitchieproducedthefirstpubliclyavailabledescriptionofC,now
knownastheK&Rstandard.
TheUNIXoperatingsystem,theCcompiler,andessentiallyallUNIXapplicationprogramshavebeen
[Link]
Easytolearn
Structuredlanguage
Itproducesefficientprograms
Itcanhandlelowlevelactivities
Itcanbecompiledonavarietyofcomputerplatforms

FactsaboutC
CwasinventedtowriteanoperatingsystemcalledUNIX.
CisasuccessorofBlanguagewhichwasintroducedaroundtheearly1970s.
Thelanguagewasformalizedin1988bytheAmericanNationalStandardInstituteAN S I .
TheUNIXOSwastotallywritteninC.
TodayCisthemostwidelyusedandpopularSystemProgrammingLanguage.
MostofthestateoftheartsoftwarehavebeenimplementedusingC.
Today'smostpopularLinuxOSandRDBMSMySQLhavebeenwritteninC.

WhyuseC?
Cwasinitiallyusedforsystemdevelopmentwork,particularlytheprogramsthatmakeupthe
[Link]
[Link]
OperatingSystems
LanguageCompilers
Assemblers
TextEditors
PrintSpoolers

[Link]

1/77

11/4/2015

CQuickGuide

NetworkDrivers
ModernPrograms
Databases
LanguageInterpreters
Utilities

CPrograms
ACprogramcanvaryfrom3linestomillionsoflinesanditshouldbewrittenintooneormoretext
fileswithextension".c"forexample,[Link]"vi","vim"oranyothertexteditortowrite
yourCprogramintoafile.
Thistutorialassumesthatyouknowhowtoeditatextfileandhowtowritesourcecodeinsidea
programfile.

CENVIRONMENTSETUP
TryitOptionOnline
WehavesetuptheCProgrammingenvironmentonline,sothatyoucancompileand
[Link]
[Link]
modifyanyexampleandexecuteitonline.
TrythefollowingexampleusingouronlinecompileravailableatCodingGround.
#include<stdio.h>
intmain(){
/*myfirstprograminC*/
printf("Hello,World!\n");

return0;
}

Formostoftheexamplesgiveninthistutorial,youwillfindaTryitoptioninour
websitecodesectionsatthetoprightcornerthatwilltakeyoutotheonlinecompiler.
Sojustmakeuseofitandenjoyyourlearning.

LocalEnvironmentSetup
IfyouwanttosetupyourenvironmentforCprogramminglanguage,youneedthefollowingtwo
softwaretoolsavailableonyourcomputer,a TextEditorandb TheCCompiler.

TextEditor
[Link],OSEdit

[Link]

2/77

11/4/2015

CQuickGuide

command,Brief,Epsilon,EMACS,andvimorvi.
[Link],Notepad
willbeusedonWindows,andvimorvicanbeusedonwindowsaswellasonLinuxorUNIX.
Thefilesyoucreatewithyoureditorarecalledthesourcefilesandtheycontaintheprogramsource
[Link]".c".
Beforestartingyourprogramming,makesureyouhaveonetexteditorinplaceandyouhaveenough
experiencetowriteacomputerprogram,saveitinafile,compileitandfinallyexecuteit.

TheCCompiler
[Link]
"compiled",intomachinelanguagesothatyourCPUcanactuallyexecutetheprogramasperthe
instructionsgiven.
[Link]
freeavailablecompileristheGNUC/C++compiler,otherwiseyoucanhavecompilerseitherfromHP
orSolarisifyouhavetherespectiveoperatingsystems.
ThefollowingsectionexplainshowtoinstallGNUC/C++[Link]
C/C++togetherbecauseGNUgcccompilerworksforbothCandC++programminglanguages.

InstallationonUNIX/Linux
IfyouareusingLinuxorUNIX,thencheckwhetherGCCisinstalledonyoursystembyenteringthe
followingcommandfromthecommandline
$gccv

IfyouhaveGNUcompilerinstalledonyourmachine,thenitshouldprintamessageasfollows
Usingbuiltinspecs.
Target:i386redhatlinux
Configuredwith:../configureprefix=/usr.......
Threadmodel:posix
gccversion4.1.220080704(RedHat4.1.246)

IfGCCisnotinstalled,thenyouwillhavetoinstallityourselfusingthedetailedinstructionsavailableat
[Link]
ThistutorialhasbeenwrittenbasedonLinuxandallthegivenexampleshavebeencompiledonthe
CentOSflavoroftheLinuxsystem.

InstallationonMacOS
IfyouuseMacOSX,theeasiestwaytoobtainGCCistodownloadtheXcodedevelopmentenvironment
fromApple'[Link],you
willbeabletouseGNUcompilerforC/C++.
[Link]/technologies/tools/.

InstallationonWindows

[Link]

3/77

11/4/2015

CQuickGuide

ToinstallGCConWindows,[Link],gototheMinGW
homepage,[Link],[Link]
versionoftheMinGWinstallationprogram,whichshouldbenamedMinGW<version>.exe.
WhileinstallingMinGW,ataminimum,youmustinstallgcccore,gccg++,binutils,andtheMinGW
runtime,butyoumaywishtoinstallmore.
AddthebinsubdirectoryofyourMinGWinstallationtoyourPATHenvironmentvariable,sothatyou
canspecifythesetoolsonthecommandlinebytheirsimplenames.
Aftertheinstallationiscomplete,youwillbeabletorungcc,g++,ar,ranlib,dlltool,andseveralother
GNUtoolsfromtheWindowscommandline.

CPROGRAMSTRUCTURE
BeforewestudythebasicbuildingblocksoftheCprogramminglanguage,letuslookatabare
minimumCprogramstructuresothatwecantakeitasareferenceintheupcomingchapters.

HelloWorldExample
ACprogrambasicallyconsistsofthefollowingparts
PreprocessorCommands
Functions
Variables
Statements&Expressions
Comments
Letuslookatasimplecodethatwouldprintthewords"HelloWorld"
#include<stdio.h>
intmain(){
/*myfirstprograminC*/
printf("Hello,World!\n");

return0;
}

Letustakealookatthevariouspartsoftheaboveprogram
Thefirstlineoftheprogram#include<stdio.h>isapreprocessorcommand,whichtellsaC
[Link].
Thenextlineintmainisthemainfunctionwheretheprogramexecutionbegins.
Thenextline/*...*/willbeignoredbythecompilerandithasbeenputtoaddadditional
[Link].
Thenextlineprintf . . . isanotherfunctionavailableinCwhichcausesthemessage"Hello,
World!"tobedisplayedonthescreen.

[Link]

4/77

11/4/2015

CQuickGuide

Thenextlinereturn0terminatesthemainfunctionandreturnsthevalue0.

CompileandExecuteCProgram
Letusseehowtosavethesourcecodeinafile,[Link]
steps
Openatexteditorandaddtheabovementionedcode.
Savethefileashello.c
Openacommandpromptandgotothedirectorywhereyouhavesavedthefile.
[Link].
Iftherearenoerrorsinyourcode,thecommandpromptwilltakeyoutothenextlineandwould
[Link].
Now,[Link].
Youwillseetheoutput"HelloWorld"printedonthescreen.
$gcchello.c
$./[Link]
Hello,World!

Makesurethegcccompilerisinyourpathandthatyouarerunningitinthedirectorycontainingthe
sourcefilehello.c.

CBASICSYNTAX
YouhaveseenthebasicstructureofaCprogram,soitwillbeeasytounderstandotherbasicbuilding
blocksoftheCprogramminglanguage.

TokensinC
ACprogramconsistsofvarioustokensandatokeniseitherakeyword,anidentifier,aconstant,a
stringliteral,[Link],thefollowingCstatementconsistsoffivetokens
printf("Hello,World!\n");

Theindividualtokensare
printf
(
"Hello,World!\n"
)
;

Semicolons
InaCprogram,[Link],eachindividualstatementmustbe
[Link].

[Link]

5/77

11/4/2015

CQuickGuide

Givenbelowaretwodifferentstatements
printf("Hello,World!\n");
return0;

Comments
[Link]
/*andterminatewiththecharacters*/asshownbelow
/*myfirstprograminC*/

Youcannothavecommentswithincommentsandtheydonotoccurwithinastringorcharacterliterals.

Identifiers
ACidentifierisanameusedtoidentifyavariable,function,[Link]
identifierstartswithaletterAtoZ,atoz,oranunderscore'_'followedbyzeroormoreletters,
underscores,anddigits0to9 .
Cdoesnotallowpunctuationcharacterssuchas@,$,and%[Link]
[Link],[Link]
someexamplesofacceptableidentifiers
mohdzaraabcmove_namea_123
myname50_tempja23b9retVal

Keywords
[Link]
variablesoranyotheridentifiernames.

auto

else

long

switch

break

enum

register

typedef

case

extern

return

union

char

float

short

unsigned

const

for

signed

void

continue

goto

sizeof

volatile

default

if

static

while

do

int

struct

_Packed

double

[Link]

6/77

11/4/2015

CQuickGuide

WhitespaceinC
Alinecontainingonlywhitespace,possiblywithacomment,isknownasablankline,andaCcompiler
totallyignoresit.
WhitespaceisthetermusedinCtodescribeblanks,tabs,newlinecharactersandcomments.
Whitespaceseparatesonepartofastatementfromanotherandenablesthecompilertoidentifywhere
oneelementinastatement,suchasint,[Link],inthefollowing
statement
intage;

theremustbeatleastonewhitespacecharacterusuallyaspace betweenintandageforthecompilerto
[Link],inthefollowingstatement
fruit=apples+oranges;//getthetotalfruit

nowhitespacecharactersarenecessarybetweenfruitand=,orbetween=andapples,althoughyouare
freetoincludesomeifyouwishtoincreasereadability.

CDATATYPES
Datatypesincrefertoanextensivesystemusedfordeclaringvariablesorfunctionsofdifferenttypes.
Thetypeofavariabledetermineshowmuchspaceitoccupiesinstorageandhowthebitpatternstored
isinterpreted.
ThetypesinCcanbeclassifiedasfollows

S.N.
1

Types&Description
BasicTypes
Theyarearithmetictypesandarefurtherclassifiedinto:a integertypesandb floatingpoint
types.

Enumeratedtypes
Theyareagainarithmetictypesandtheyareusedtodefinevariablesthatcanonlyassign
certaindiscreteintegervaluesthroughouttheprogram.

Thetypevoid
Thetypespecifiervoidindicatesthatnovalueisavailable.

[Link]

7/77

11/4/2015

CQuickGuide

Derivedtypes
Theyincludea Pointertypes,b Arraytypes,c Structuretypes,d UniontypesandeFunction
types.

[Link]
functionspecifiesthetypeofthefunction'[Link]
section,whereasothertypeswillbecoveredintheupcomingchapters.

IntegerTypes
Thefollowingtableprovidesthedetailsofstandardintegertypeswiththeirstoragesizesandvalue
ranges

Type

Storagesize

Valuerange

char

1byte

128to127or0to255

unsignedchar

1byte

0to255

signedchar

1byte

128to127

int

2or4bytes

32,768to32,767or2,147,483,648to2,147,483,647

unsignedint

2or4bytes

0to65,535or0to4,294,967,295

short

2bytes

32,768to32,767

unsignedshort

2bytes

0to65,535

long

4bytes

2,147,483,648to2,147,483,647

unsignedlong

4bytes

0to4,294,967,295

Togettheexactsizeofatypeoravariableonaparticularplatform,youcanusethesizeofoperator.
Theexpressionssizeof [Link]
exampletogetthesizeofinttypeonanymachine
#include<stdio.h>
#include<limits.h>
intmain(){
printf("Storagesizeforint:%d\n",sizeof(int));

return0;

[Link]

8/77

11/4/2015

CQuickGuide

Whenyoucompileandexecutetheaboveprogram,itproducesthefollowingresultonLinux
Storagesizeforint:4

FloatingPointTypes
Thefollowingtableprovidethedetailsofstandardfloatingpointtypeswithstoragesizesandvalue
rangesandtheirprecision

Type

Storagesize

Valuerange

Precision

float

4byte

1.2E38to3.4E+38

6decimalplaces

double

8byte

2.3E308to1.7E+308

15decimalplaces

longdouble

10byte

3.4E4932to1.1E+4932

19decimalplaces

[Link]
[Link]
spacetakenbyafloattypeanditsrangevalues
#include<stdio.h>
#include<float.h>
intmain(){
printf("Storagesizeforfloat:%d\n",sizeof(float));
printf("Minimumfloatpositivevalue:%E\n",FLT_MIN);
printf("Maximumfloatpositivevalue:%E\n",FLT_MAX);
printf("Precisionvalue:%d\n",FLT_DIG);

return0;
}

Whenyoucompileandexecutetheaboveprogram,itproducesthefollowingresultonLinux
Storagesizeforfloat:4
Minimumfloatpositivevalue:1.175494E38
Maximumfloatpositivevalue:3.402823E+38
Precisionvalue:6

ThevoidType
[Link]

S.N.

[Link]

Types&Description

9/77

11/4/2015

CQuickGuide

Functionreturnsasvoid
TherearevariousfunctionsinCwhichdonotreturnanyvalueoryoucansaytheyreturn
[Link],voidexit
intstatus

Functionargumentsasvoid
[Link]
[Link],intrandvoid

Pointerstovoid
Apointeroftypevoid*representstheaddressofanobject,[Link],a
memoryallocationfunctionvoid*mallocsize sizereturnsapointertovoidwhichcanbe
castedtoanydatatype.
t

CVARIABLES
[Link]
variableinChasaspecifictype,whichdeterminesthesizeandlayoutofthevariable'smemorythe
rangeofvaluesthatcanbestoredwithinthatmemoryandthesetofoperationsthatcanbeappliedto
thevariable.
Thenameofavariablecanbecomposedofletters,digits,[Link]
[Link]
[Link],therewillbethefollowingbasic
variabletypes

Type

Description

char

Typicallyasingleoctetonebyte .Thisisanintegertype.

int

Themostnaturalsizeofintegerforthemachine.

float

Asingleprecisionfloatingpointvalue.

double

Adoubleprecisionfloatingpointvalue.

void

Representstheabsenceoftype.

[Link]

10/77

11/4/2015

CQuickGuide

Cprogramminglanguagealsoallowstodefinevariousothertypesofvariables,whichwewillcoverin
subsequentchapterslikeEnumeration,Pointer,Array,Structure,Union,[Link],letus
studyonlybasicvariabletypes.

VariableDefinitioninC
Avariabledefinitiontellsthecompilerwhereandhowmuchstoragetocreateforthevariable.A
variabledefinitionspecifiesadatatypeandcontainsalistofoneormorevariablesofthattypeas
follows
typevariable_list;

Here,typemustbeavalidCdatatypeincludingchar,w_char,int,float,double,bool,oranyuser
definedobjectandvariable_listmayconsistofoneormoreidentifiernamesseparatedbycommas.
Somevaliddeclarationsareshownhere
inti,j,k;
charc,ch;
floatf,salary;
doubled;

Thelineinti,j,kdeclaresanddefinesthevariablesi,j,andkwhichinstructthecompilertocreate
variablesnamedi,jandkoftypeint.
[Link]
equalsignfollowedbyaconstantexpressionasfollows
typevariable_name=value;

Someexamplesare
externintd=3,f=5;//declarationofdandf.
intd=3,f=5;//definitionandinitializingdandf.
bytez=22;//definitionandinitializesz.
charx='x';//thevariablexhasthevalue'x'.

Fordefinitionwithoutaninitializer:variableswithstaticstoragedurationareimplicitlyinitializedwith
NULLallbyteshavethevalue0theinitialvalueofallothervariablesareundefined.

VariableDeclarationinC
Avariabledeclarationprovidesassurancetothecompilerthatthereexistsavariablewiththegiventype
andnamesothatthecompilercanproceedforfurthercompilationwithoutrequiringthecomplete
[Link],the
compilerneedsactualvariabledeclarationatthetimeoflinkingtheprogram.
Avariabledeclarationisusefulwhenyouareusingmultiplefilesandyoudefineyourvariableinoneof
[Link]
[Link],
itcanbedefinedonlyonceinafile,afunction,orablockofcode.

Example

[Link]

11/77

11/4/2015

CQuickGuide

Trythefollowingexample,wherevariableshavebeendeclaredatthetop,buttheyhavebeendefined
andinitializedinsidethemainfunction
#include<stdio.h>
//Variabledeclaration:
externinta,b;
externintc;
externfloatf;
intmain(){
/*variabledefinition:*/
inta,b;
intc;
floatf;

/*actualinitialization*/
a=10;
b=20;

c=a+b;
printf("valueofc:%d\n",c);
f=70.0/3.0;
printf("valueoff:%f\n",f);

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
valueofc:30
valueoff:23.333334

Thesameconceptappliesonfunctiondeclarationwhereyouprovideafunctionnameatthetimeofits
[Link]
//functiondeclaration
intfunc();
intmain(){
//functioncall
inti=func();
}
//functiondefinition
intfunc(){
return0;
}

LvaluesandRvaluesinC
TherearetwokindsofexpressionsinC

[Link]

12/77

11/4/2015

CQuickGuide

lvalueExpressionsthatrefertoamemorylocationarecalled"lvalue"[Link]
mayappearaseitherthelefthandorrighthandsideofanassignment.
[Link]
rvalueisanexpressionthatcannothaveavalueassignedtoitwhichmeansanrvaluemayappear
ontherighthandsidebutnotonthelefthandsideofanassignment.
[Link]
[Link]
followingvalidandinvalidstatements
intg=20;//validstatement
10=20;//invalidstatement;wouldgeneratecompiletimeerror

CCONSTANTS&LITERALS
[Link]
arealsocalledliterals.
Constantscanbeofanyofthebasicdatatypeslikeanintegerconstant,afloatingconstant,acharacter
constant,[Link].
Constantsaretreatedjustlikeregularvariablesexceptthattheirvaluescannotbemodifiedaftertheir
definition.

IntegerLiterals
Anintegerliteralcanbeadecimal,octal,[Link]:
0xor0Xforhexadecimal,0foroctal,andnothingfordecimal.
AnintegerliteralcanalsohaveasuffixthatisacombinationofUandL,forunsignedandlong,
[Link].
Herearesomeexamplesofintegerliterals
212/*Legal*/
215u/*Legal*/
0xFeeL/*Legal*/
078/*Illegal:8isnotanoctaldigit*/
032UU/*Illegal:cannotrepeatasuffix*/

Followingareotherexamplesofvarioustypesofintegerliterals
85/*decimal*/
0213/*octal*/
0x4b/*hexadecimal*/
30/*int*/
30u/*unsignedint*/
30l/*long*/
30ul/*unsignedlong*/

FloatingpointLiterals

[Link]

13/77

11/4/2015

CQuickGuide

Afloatingpointliteralhasanintegerpart,adecimalpoint,afractionalpart,[Link]
canrepresentfloatingpointliteralseitherindecimalformorexponentialform.
Whilerepresentingdecimalform,youmustincludethedecimalpoint,theexponent,orbothandwhile
representingexponentialform,youmustincludetheintegerpart,thefractionalpart,[Link]
signedexponentisintroducedbyeorE.
Herearesomeexamplesoffloatingpointliterals
3.14159/*Legal*/
314159E5L/*Legal*/
510E/*Illegal:incompleteexponent*/
210f/*Illegal:nodecimalorexponent*/
.e55/*Illegal:missingintegerorfraction*/

CharacterConstants
Characterliteralsareenclosedinsinglequotes,e.g.,'x'canbestoredinasimplevariableofchartype.
Acharacterliteralcanbeaplaincharactere. g. ,
charactere. g. , \u02C 0 .

,anescapesequencee. g. ,

\t

,orauniversal

TherearecertaincharactersinCthatrepresentspecialmeaningwhenprecededbyabackslashfor
example,newline\n ortab\t .
Here,youhavealistofsuchescapesequencecodes

Escapesequence

Meaning

\\

\character

\'

'character

\"

"character

\?

?character

\a

Alertorbell

\b

Backspace

\f

Formfeed

\n

Newline

\r

Carriagereturn

\t

Horizontaltab

\v

Verticaltab

[Link]

14/77

11/4/2015

CQuickGuide

\ooo

Octalnumberofonetothreedigits

\xhh...

Hexadecimalnumberofoneormoredigits

Followingistheexampletoshowafewescapesequencecharacters
#include<stdio.h>
intmain(){
printf("Hello\tWorld\n\n");
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
HelloWorld

StringLiterals
Stringliteralsorconstantsareenclosedindoublequotes"".Astringcontainscharactersthatare
similartocharacterliterals:plaincharacters,escapesequences,anduniversalcharacters.
Youcanbreakalonglineintomultiplelinesusingstringliteralsandseparatingthemusingwhite
spaces.
[Link].
"hello,dear"
"hello,\
dear"
"hello,""d""ear"

DefiningConstants
TherearetwosimplewaysinCtodefineconstants
Using#definepreprocessor.
Usingconstkeyword.

The#definePreprocessor
Givenbelowistheformtouse#definepreprocessortodefineaconstant
#defineidentifiervalue

Thefollowingexampleexplainsitindetail

[Link]

15/77

11/4/2015

CQuickGuide

#include<stdio.h>
#defineLENGTH10
#defineWIDTH5
#defineNEWLINE'\n'
intmain(){
intarea;

area=LENGTH*WIDTH;
printf("valueofarea:%d",area);
printf("%c",NEWLINE);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
valueofarea:50

TheconstKeyword
Youcanuseconstprefixtodeclareconstantswithaspecifictypeasfollows
consttypevariable=value;

Thefollowingexampleexplainsitindetail
#include<stdio.h>
intmain(){
constintLENGTH=10;
constintWIDTH=5;
constcharNEWLINE='\n';
intarea;

area=LENGTH*WIDTH;
printf("valueofarea:%d",area);
printf("%c",NEWLINE);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
valueofarea:50

NotethatitisagoodprogrammingpracticetodefineconstantsinCAPITALS.

CSTORAGECLASSES

[Link]

16/77

11/4/2015

CQuickGuide

Astorageclassdefinesthescopevisibility andlifetimeofvariablesand/orfunctionswithinaC
[Link]
program
auto
register
static
extern

TheautoStorageClass
Theautostorageclassisthedefaultstorageclassforalllocalvariables.
{
intmount;
autointmonth;
}

Theexampleabovedefinestwovariableswithinthesamestorageclass.'auto'canonlybeusedwithin
functions,i.e.,localvariables.

TheregisterStorageClass
Theregisterstorageclassisusedtodefinelocalvariablesthatshouldbestoredinaregisterinsteadof
[Link] and
can'thavetheunary'&'operatorappliedtoitasitdoesnothaveamemorylocation .
{
registerintmiles;
}

[Link]
benotedthatdefining'register'[Link]
thatitMIGHTbestoredinaregisterdependingonhardwareandimplementationrestrictions.

ThestaticStorageClass
Thestaticstorageclassinstructsthecompilertokeepalocalvariableinexistenceduringthelifetime
oftheprograminsteadofcreatinganddestroyingiteachtimeitcomesintoandgoesoutofscope.
Therefore,makinglocalvariablesstaticallowsthemtomaintaintheirvaluesbetweenfunctioncalls.
[Link],itcausesthatvariable's
scopetoberestrictedtothefileinwhichitisdeclared.
InCprogramming,whenstaticisusedonaclassdatamember,itcausesonlyonecopyofthatmember
tobesharedbyalltheobjectsofitsclass.
#include<stdio.h>

/*functiondeclaration*/
voidfunc(void);

[Link]

17/77

11/4/2015

CQuickGuide

staticintcount=5;/*globalvariable*/

main(){
while(count){
func();
}

return0;
}
/*functiondefinition*/
voidfunc(void){
staticinti=5;/*localstaticvariable*/
i++;
printf("iis%dandcountis%d\n",i,count);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
iis6andcountis4
iis7andcountis3
iis8andcountis2
iis9andcountis1
iis10andcountis0

TheexternStorageClass
TheexternstorageclassisusedtogiveareferenceofaglobalvariablethatisvisibletoALLthe
[Link]'extern',thevariablecannotbeinitializedhowever,itpointsthevariable
nameatastoragelocationthathasbeenpreviouslydefined.
Whenyouhavemultiplefilesandyoudefineaglobalvariableorfunction,whichwillalsobeusedin
otherfiles,thenexternwillbeusedinanotherfiletoprovidethereferenceofdefinedvariableor
[Link],externisusedtodeclareaglobalvariableorfunctioninanotherfile.
Theexternmodifierismostcommonlyusedwhentherearetwoormorefilessharingthesameglobal
variablesorfunctionsasexplainedbelow.
FirstFile:main.c
#include<stdio.h>

intcount;
externvoidwrite_extern();

main(){
count=5;
write_extern();
}

SecondFile:support.c

[Link]

18/77

11/4/2015

CQuickGuide

#include<stdio.h>

externintcount;

voidwrite_extern(void){
printf("countis%d\n",count);
}

Here,externisbeingusedtodeclarecountinthesecondfile,whereasithasitsdefinitioninthefirst
file,[Link],compilethesetwofilesasfollows
$[Link].c

[Link],itproducesthefollowing
result
5

COPERATORS
Anoperatorisasymbolthattellsthecompilertoperformspecificmathematicalorlogicalfunctions.C
languageisrichinbuiltinoperatorsandprovidesthefollowingtypesofoperators
ArithmeticOperators
RelationalOperators
LogicalOperators
BitwiseOperators
AssignmentOperators
MiscOperators
Wewill,inthischapter,lookintothewayeachoperatorworks.

ArithmeticOperators
[Link]
holds10andvariableBholds20then
ShowExamples

Operator

Description

Example

Addstwooperands.

A+B=30

Subtractssecondoperandfromthefirst.

AB=10

Multipliesbothoperands.

A*B=200

Dividesnumeratorbydenumerator.

B/A=2

[Link]

19/77

11/4/2015

CQuickGuide

ModulusOperatorandremainderofafteraninteger
division.

B%A=0

++

Incrementoperatorincreasestheintegervalueby
one.

A++=11

Decrementoperatordecreasestheintegervalueby
one.

A=9

RelationalOperators
ThefollowingtableshowsalltherelationaloperatorssupportedbyC.AssumevariableAholds10and
variableBholds20then
ShowExamples

Operator

Description

==

Checksifthevaluesoftwooperandsareequalornot.
Ifyes,thentheconditionbecomestrue.

!=

Checksifthevaluesoftwooperandsareequalornot.
Ifthevaluesarenotequal,thenthecondition
becomestrue.

>

Checksifthevalueofleftoperandisgreaterthanthe
[Link],thenthecondition
becomestrue.

<

Checksifthevalueofleftoperandislessthanthe
[Link],thenthecondition
becomestrue.

>=

Checksifthevalueofleftoperandisgreaterthanor
[Link],thenthe
conditionbecomestrue.

<=

Checksifthevalueofleftoperandislessthanor
[Link],thenthe
conditionbecomestrue.

Example
A == B

A! = B

isnottrue.

istrue.

A > B

isnottrue.

A < B

istrue.

A >= B

isnottrue.

A <= B

istrue.

LogicalOperators

[Link]

20/77

11/4/2015

CQuickGuide

FollowingtableshowsallthelogicaloperatorssupportedbyClanguage.AssumevariableAholds1and
variableBholds0,then
ShowExamples

Operator

Description

Example

&&

[Link]
arenonzero,thentheconditionbecomestrue.

||

[Link]
operandsisnonzero,thentheconditionbecomes
true.

[Link]
[Link],then
LogicalNOToperatorwillmakeitfalse.

A&&B isfalse.

A||B

istrue.

! A&&B istrue.

BitwiseOperators
[Link]&,|,and^isas
follows

p&q

p|q

p^q

AssumeA=60andB=13inbinaryformat,theywillbeasfollows
A=00111100
B=00001101

A&B=00001100
A|B=00111101
A^B=00110001

[Link]

21/77

11/4/2015

CQuickGuide

~A=11000011
[Link]'A'holds60and
variable'B'holds13,then
ShowExamples

Operator

Description

Example

&

BinaryANDOperatorcopiesabittotheresultifit
existsinbothoperands.

BinaryOROperatorcopiesabitifitexistsineither
operand.

BinaryXOROperatorcopiesthebitifitissetinone
operandbutnotboth.

BinaryOnesComplementOperatorisunaryandhas
theeffectof'flipping'bits.

=61,i.e,.11000011in2's
complementform.

<<

[Link]
movedleftbythenumberofbitsspecifiedbythe
rightoperand.

A<<2=240i.e.,11110000

>>

[Link]
ismovedrightbythenumberofbitsspecifiedbythe
rightoperand.

A>>2=15i.e.,00001111

A&B =12,i.e.,00001100

A|B

=61,i.e.,00111101

=49,i.e.,00110001

AssignmentOperators
ThefollowingtableliststheassignmentoperatorssupportedbytheClanguage
ShowExamples

Operator

Description

Example

[Link]
rightsideoperandstoleftsideoperand

C=A+Bwillassignthevalue
ofA+BtoC

+=

[Link]
operandtotheleftoperandandassigntheresultto
theleftoperand.

C+=AisequivalenttoC=C
+A

[Link]

C=AisequivalenttoC=C

[Link]

22/77

11/4/2015

CQuickGuide

rightoperandfromtheleftoperandandassignsthe
resulttotheleftoperand.

*=

[Link]
rightoperandwiththeleftoperandandassignsthe
resulttotheleftoperand.

C*=AisequivalenttoC=C*
A

/=

[Link]
operandwiththerightoperandandassignstheresult
totheleftoperand.

C/=AisequivalenttoC=C/
A

%=

[Link]
usingtwooperandsandassignstheresulttotheleft
operand.

C%=AisequivalenttoC=C
%A

<<=

LeftshiftANDassignmentoperator.

C<<=2issameasC=C<<2

>>=

RightshiftANDassignmentoperator.

C>>=2issameasC=C>>2

&=

BitwiseANDassignmentoperator.

C&=2issameasC=C&2

^=

BitwiseexclusiveORandassignmentoperator.

C^=2issameasC=C^2

|=

BitwiseinclusiveORandassignmentoperator.

C|=2issameasC=C|2

MiscOperatorssizeof&ternary
Besidestheoperatorsdiscussedabove,thereareafewotherimportantoperatorsincludingsizeofand
?:supportedbytheCLanguage.
ShowExamples

Operator

Description

Example

sizeof

Returnsthesizeofavariable.

sizeof a ,whereaisinteger,
willreturn4.

&

Returnstheaddressofavariable.

&areturnstheactualaddress
ofthevariable.

Pointertoavariable.

*a

?:

ConditionalExpression.

IfConditionistrue?then
valueX:otherwisevalueY

[Link]

23/77

11/4/2015

CQuickGuide

OperatorsPrecedenceinC
Operatorprecedencedeterminesthegroupingoftermsinanexpressionanddecideshowanexpression
[Link],themultiplication
operatorhasahigherprecedencethantheadditionoperator.
Forexample,x=7+3*2here,xisassigned13,not20becauseoperator*hasahigherprecedence
than+,soitfirstgetsmultipliedwith3*2andthenaddsinto7.
Here,operatorswiththehighestprecedenceappearatthetopofthetable,thosewiththelowestappear
[Link],higherprecedenceoperatorswillbeevaluatedfirst.
ShowExamples

Category

Operator

Associativity

Postfix

[]>.++

Lefttoright

Unary

+!~++type*&sizeof

Righttoleft

Multiplicative

*/%

Lefttoright

Additive

Lefttoright

Shift

<<>>

Lefttoright

Relational

<<=>>=

Lefttoright

Equality

==!=

Lefttoright

BitwiseAND

&

Lefttoright

BitwiseXOR

Lefttoright

BitwiseOR

Lefttoright

LogicalAND

&&

Lefttoright

LogicalOR

||

Lefttoright

Conditional

?:

Righttoleft

Assignment

=+==*=/=%=>>=<<=&=^=|=

Righttoleft

Comma

Lefttoright

CDECISIONMAKING

[Link]

24/77

11/4/2015

CQuickGuide

Decisionmakingstructuresrequirethattheprogrammerspecifiesoneormoreconditionstobe
evaluatedortestedbytheprogram,alongwithastatementorstatementstobeexecutedifthe
conditionisdeterminedtobetrue,andoptionally,otherstatementstobeexecutediftheconditionis
determinedtobefalse.
Showbelowisthegeneralformofatypicaldecisionmakingstructurefoundinmostofthe
programminglanguages

Cprogramminglanguageassumesanynonzeroandnonnullvaluesastrue,andifitiseitherzero
ornull,thenitisassumedasfalsevalue.
Cprogramminglanguageprovidesthefollowingtypesofdecisionmakingstatements.

[Link].

Statement&Description

ifstatement
Anifstatementconsistsofabooleanexpressionfollowedbyoneormorestatements.

if...elsestatement
Anifstatementcanbefollowedbyanoptionalelsestatement,whichexecuteswhen
theBooleanexpressionisfalse.

nestedifstatements
Youcanuseoneiforelseifstatementinsideanotheriforelseifstatements.

[Link]

25/77

11/4/2015

CQuickGuide

switchstatement
Aswitchstatementallowsavariabletobetestedforequalityagainstalistofvalues.

nestedswitchstatements
Youcanuseoneswitchstatementinsideanotherswitchstatements.

The?:Operator
Wehavecoveredconditionaloperator?:inthepreviouschapterwhichcanbeusedtoreplace
if...[Link]
Exp1?Exp2:Exp3;

WhereExp1,Exp2,[Link].
Thevalueofa?expressionisdeterminedlikethis
[Link],thenExp2isevaluatedandbecomesthevalueoftheentire?
expression.
IfExp1isfalse,thenExp3isevaluatedanditsvaluebecomesthevalueoftheexpression.

CLOOPS
Youmayencountersituations,[Link]
general,statementsareexecutedsequentially:Thefirststatementinafunctionisexecutedfirst,
followedbythesecond,andsoon.
Programminglanguagesprovidevariouscontrolstructuresthatallowformorecomplicatedexecution
paths.
[Link]
thegeneralformofaloopstatementinmostoftheprogramminglanguages

[Link]

26/77

11/4/2015

CQuickGuide

Cprogramminglanguageprovidesthefollowingtypesofloopstohandleloopingrequirements.

[Link].

LoopType&Description

whileloop
[Link]
conditionbeforeexecutingtheloopbody.

forloop
Executesasequenceofstatementsmultipletimesandabbreviatesthecodethatmanages
theloopvariable.

do...whileloop
Itismorelikeawhilestatement,exceptthatitteststheconditionattheendoftheloop
body.

nestedloops
Youcanuseoneormoreloopsinsideanyotherwhile,for,ordo..whileloop.

[Link]

27/77

11/4/2015

CQuickGuide

LoopControlStatements
[Link],
allautomaticobjectsthatwerecreatedinthatscopearedestroyed.
Csupportsthefollowingcontrolstatements.

[Link].

ControlStatement&Description

breakstatement
Terminatesthelooporswitchstatementandtransfersexecutiontothestatement
immediatelyfollowingthelooporswitch.

continuestatement
Causesthelooptoskiptheremainderofitsbodyandimmediatelyretestitsconditionprior
toreiterating.

gotostatement
Transferscontroltothelabeledstatement.

TheInfiniteLoop
[Link]
[Link]'for'looparerequired,youcan
makeanendlessloopbyleavingtheconditionalexpressionempty.
#include<stdio.h>

intmain(){
for(;;){
printf("Thisloopwillrunforever.\n");
}
return0;
}

Whentheconditionalexpressionisabsent,[Link]
incrementexpression,butCprogrammersmorecommonlyusethefor; ; constructtosignifyaninfinite
loop.
NOTEYoucanterminateaninfiniteloopbypressingCtrl+Ckeys.

CFUNCTIONS

[Link]

28/77

11/4/2015

CQuickGuide

[Link]
function,whichismain,andallthemosttrivialprogramscandefineadditionalfunctions.
[Link]
functionsisuptoyou,butlogicallythedivisionissuchthateachfunctionperformsaspecifictask.
Afunctiondeclarationtellsthecompileraboutafunction'sname,returntype,andparameters.A
functiondefinitionprovidestheactualbodyofthefunction.
[Link],
strcattoconcatenatetwostrings,memcpytocopyonememorylocationtoanotherlocation,and
manymorefunctions.
Afunctioncanalsobereferredasamethodorasubroutineoraprocedure,etc.

DefiningaFunction
ThegeneralformofafunctiondefinitioninCprogramminglanguageisasfollows
return_typefunction_name(parameterlist){
bodyofthefunction
}

[Link]
thepartsofafunction
ReturnTypeAfunctionmayreturnavalue.Thereturn_typeisthedatatypeofthevalue
[Link].
Inthiscase,thereturn_typeisthekeywordvoid.
[Link]
parameterlisttogetherconstitutethefunctionsignature.
[Link],youpassavalueto
[Link]
referstothetype,order,[Link]
thatis,afunctionmaycontainnoparameters.
FunctionBodyThefunctionbodycontainsacollectionofstatementsthatdefinewhatthe
functiondoes.

Example
Givenbelowisthesourcecodeforafunctioncalledmax.Thisfunctiontakestwoparametersnum1and
num2andreturnsthemaximumvaluebetweenthetwo
/*functionreturningthemaxbetweentwonumbers*/
intmax(intnum1,intnum2){
/*localvariabledeclaration*/
intresult;

if(num1>num2)
result=num1;

[Link]

29/77

11/4/2015

CQuickGuide

else
result=num2;

returnresult;
}

FunctionDeclarations
[Link]
actualbodyofthefunctioncanbedefinedseparately.
Afunctiondeclarationhasthefollowingparts
return_typefunction_name(parameterlist);

Fortheabovedefinedfunctionmax,thefunctiondeclarationisasfollows
intmax(intnum1,intnum2);

Parameternamesarenotimportantinfunctiondeclarationonlytheirtypeisrequired,sothefollowing
isalsoavaliddeclaration
intmax(int,int);

Functiondeclarationisrequiredwhenyoudefineafunctioninonesourcefileandyoucallthatfunction
[Link],youshoulddeclarethefunctionatthetopofthefilecallingthefunction.

CallingaFunction
WhilecreatingaCfunction,[Link],you
willhavetocallthatfunctiontoperformthedefinedtask.
Whenaprogramcallsafunction,[Link]
functionperformsadefinedtaskandwhenitsreturnstatementisexecutedorwhenitsfunctionending
closingbraceisreached,itreturnstheprogramcontrolbacktothemainprogram.
Tocallafunction,yousimplyneedtopasstherequiredparametersalongwiththefunctionname,andif
thefunctionreturnsavalue,[Link]
#include<stdio.h>

/*functiondeclaration*/
intmax(intnum1,intnum2);

intmain(){
/*localvariabledefinition*/
inta=100;
intb=200;
intret;

/*callingafunctiontogetmaxvalue*/
ret=max(a,b);

[Link]

30/77

11/4/2015

CQuickGuide

printf("Maxvalueis:%d\n",ret);

return0;
}

/*functionreturningthemaxbetweentwonumbers*/
intmax(intnum1,intnum2){
/*localvariabledeclaration*/
intresult;

if(num1>num2)
result=num1;
else
result=num2;

returnresult;
}

[Link],it
wouldproducethefollowingresult
Maxvalueis:200

FunctionArguments
Ifafunctionistousearguments,itmustdeclarevariablesthatacceptthevaluesofthearguments.
Thesevariablesarecalledtheformalparametersofthefunction.
Formalparametersbehavelikeotherlocalvariablesinsidethefunctionandarecreateduponentryinto
thefunctionanddestroyeduponexit.
Whilecallingafunction,therearetwowaysinwhichargumentscanbepassedtoafunction

[Link].

CallType&Description

Callbyvalue
Thismethodcopiestheactualvalueofanargumentintotheformalparameterofthe
[Link],changesmadetotheparameterinsidethefunctionhavenoeffecton
theargument.

Callbyreference
[Link]
function,[Link]
changesmadetotheparameteraffecttheargument.

[Link]

31/77

11/4/2015

CQuickGuide

Bydefault,[Link],itmeansthecodewithinafunction
cannotaltertheargumentsusedtocallthefunction.

CSCOPERULES
Ascopeinanyprogrammingisaregionoftheprogramwhereadefinedvariablecanhaveitsexistence
[Link]
inCprogramminglanguage
Insideafunctionorablockwhichiscalledlocalvariables.
Outsideofallfunctionswhichiscalledglobalvariables.
Inthedefinitionoffunctionparameterswhicharecalledformalparameters.
Letusunderstandwhatarelocalandglobalvariables,andformalparameters.

LocalVariables
[Link]
[Link]
[Link],
b,andcarelocaltomainfunction.
#include<stdio.h>

intmain(){
/*localvariabledeclaration*/
inta,b;
intc;

/*actualinitialization*/
a=10;
b=20;
c=a+b;

printf("valueofa=%d,b=%dandc=%d\n",a,b,c);

return0;
}

GlobalVariables
Globalvariablesaredefinedoutsideafunction,[Link]
theirvaluesthroughoutthelifetimeofyourprogramandtheycanbeaccessedinsideanyofthe
functionsdefinedfortheprogram.
[Link],aglobalvariableisavailableforuse
[Link]
areusedinaprogram.
#include<stdio.h>

[Link]

32/77

11/4/2015

CQuickGuide

/*globalvariabledeclaration*/
intg;

intmain(){
/*localvariabledeclaration*/
inta,b;

/*actualinitialization*/
a=10;
b=20;
g=a+b;

printf("valueofa=%d,b=%dandg=%d\n",a,b,g);

return0;
}

Aprogramcanhavesamenameforlocalandglobalvariablesbutthevalueoflocalvariableinsidea
[Link]
#include<stdio.h>

/*globalvariabledeclaration*/
intg=20;

intmain(){
/*localvariabledeclaration*/
intg=10;

printf("valueofg=%d\n",g);

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
valueofg=10

FormalParameters
Formalparameters,aretreatedaslocalvariableswithinafunctionandtheytakeprecedenceover
[Link]
#include<stdio.h>

/*globalvariabledeclaration*/
inta=20;

intmain(){
/*localvariabledeclarationinmainfunction*/
inta=10;
intb=20;

[Link]

33/77

11/4/2015

CQuickGuide

intc=0;
printf("valueofainmain()=%d\n",a);
c=sum(a,b);
printf("valueofcinmain()=%d\n",c);
return0;
}
/*functiontoaddtwointegers*/
intsum(inta,intb){
printf("valueofainsum()=%d\n",a);
printf("valueofbinsum()=%d\n",b);
returna+b;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
valueofainmain()=10
valueofainsum()=10
valueofbinsum()=20
valueofcinmain()=30

InitializingLocalandGlobalVariables
Whenalocalvariableisdefined,itisnotinitializedbythesystem,[Link]
variablesareinitializedautomaticallybythesystemwhenyoudefinethemasfollows

DataType

InitialDefaultValue

int

char

'\0'

float

double

pointer

NULL

Itisagoodprogrammingpracticetoinitializevariablesproperly,otherwiseyourprogrammayproduce
unexpectedresults,becauseuninitializedvariableswilltakesomegarbagevaluealreadyavailableat
theirmemorylocation.

CARRAYS
Arraysakindofdatastructurethatcanstoreafixedsizesequentialcollectionofelementsofthesame
[Link],butitisoftenmoreusefultothinkofanarrayasa

[Link]

34/77

11/4/2015

CQuickGuide

collectionofvariablesofthesametype.
Insteadofdeclaringindividualvariables,suchasnumber0,number1,...,andnumber99,youdeclare
onearrayvariablesuchasnumbersandusenumbers[0],numbers[1],and...,numbers[99]torepresent
[Link].
[Link]
andthehighestaddresstothelastelement.

DeclaringArrays
TodeclareanarrayinC,aprogrammerspecifiesthetypeoftheelementsandthenumberofelements
requiredbyanarrayasfollows
typearrayName[arraySize];

[Link]
[Link],todeclarea10elementarraycalledbalanceof
typedouble,usethisstatement
doublebalance[10];

Herebalanceisavariablearraywhichissufficienttoholdupto10doublenumbers.

InitializingArrays
YoucaninitializeanarrayinCeitheronebyoneorusingasinglestatementasfollows
doublebalance[5]={1000.0,2.0,3.4,7.0,50.0};

Thenumberofvaluesbetweenbraces{}cannotbelargerthanthenumberofelementsthatwedeclare
forthearraybetweensquarebrackets[].
Ifyouomitthesizeofthearray,[Link],
ifyouwrite
doublebalance[]={1000.0,2.0,3.4,7.0,50.0};

[Link]
assignasingleelementofthearray
balance[4]=50.0;

Theabovestatementassignsthe5thelementinthearraywithavalueof50.0.Allarrayshave0asthe
indexoftheirfirstelementwhichisalsocalledthebaseindexandthelastindexofanarraywillbetotal

[Link]

35/77

11/4/2015

CQuickGuide

[Link]

AccessingArrayElements
[Link]
[Link]
doublesalary=balance[9];

Theabovestatementwilltakethe10thelementfromthearrayandassignthevaluetosalaryvariable.
[Link],
assignment,andaccessingarrays
#include<stdio.h>

intmain(){
intn[10];/*nisanarrayof10integers*/
inti,j;

/*initializeelementsofarraynto0*/
for(i=0;i<10;i++){
n[i]=i+100;/*setelementatlocationitoi+100*/
}

/*outputeacharrayelement'svalue*/
for(j=0;j<10;j++){
printf("Element[%d]=%d\n",j,n[j]);
}

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Element[0]=100
Element[1]=101
Element[2]=102
Element[3]=103
Element[4]=104
Element[5]=105
Element[6]=106
Element[7]=107
Element[8]=108
Element[9]=109

ArraysinDetail
[Link]

[Link]

36/77

11/4/2015

CQuickGuide

relatedtoarrayshouldbecleartoaCprogrammer

[Link].

Concept&Description

Multidimensionalarrays
[Link]
thetwodimensionalarray.

Passingarraystofunctions
Youcanpasstothefunctionapointertoanarraybyspecifyingthearray'snamewithoutan
index.

Returnarrayfromafunction
Callowsafunctiontoreturnanarray.

Pointertoanarray
Youcangenerateapointertothefirstelementofanarraybysimplyspecifyingthearray
name,withoutanyindex.

CPOINTERS
[Link]
pointers,andothertasks,suchasdynamicmemoryallocation,cannotbeperformedwithoutusing
[Link]'sstart
learningtheminsimpleandeasysteps.
Asyouknow,everyvariableisamemorylocationandeverymemorylocationhasitsaddressdefined
whichcanbeaccessedusingampersand & operator,[Link]
thefollowingexample,whichprintstheaddressofthevariablesdefined
#include<stdio.h>
intmain(){
intvar1;
charvar2[10];
printf("Addressofvar1variable:%x\n",&var1);
printf("Addressofvar2variable:%x\n",&var2);
return0;

[Link]

37/77

11/4/2015

CQuickGuide

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Addressofvar1variable:bff5a400
Addressofvar2variable:bff5a3f6

WhatarePointers?
Apointerisavariablewhosevalueistheaddressofanothervariable,i.e.,directaddressofthe
[Link],youmustdeclareapointerbeforeusingittostoreany
[Link]
type*varname;

Here,typeisthepointer'sbasetypeitmustbeavalidCdatatypeandvarnameisthenameofthe
[Link]*usedtodeclareapointeristhesameasteriskusedformultiplication.
However,[Link]
someofthevalidpointerdeclarations
int*ip;/*pointertoaninteger*/
double*dp;/*pointertoadouble*/
float*fp;/*pointertoafloat*/
char*ch/*pointertoacharacter*/

Theactualdatatypeofthevalueofallpointers,whetherinteger,float,character,orotherwise,isthe
same,[Link]
pointersofdifferentdatatypesisthedatatypeofthevariableorconstantthatthepointerpointsto.

HowtoUsePointers?
Thereareafewimportantoperations,whichwewilldowiththehelpofpointersveryfrequently.a We
defineapointervariable,b assigntheaddressofavariabletoapointerandc finallyaccessthevalueat
[Link]*thatreturnsthe
[Link]
oftheseoperations
#include<stdio.h>
intmain(){
intvar=20;/*actualvariabledeclaration*/
int*ip;/*pointervariabledeclaration*/
ip=&var;/*storeaddressofvarinpointervariable*/
printf("Addressofvarvariable:%x\n",&var);
/*addressstoredinpointervariable*/
printf("Addressstoredinipvariable:%x\n",ip);
/*accessthevalueusingthepointer*/
printf("Valueof*ipvariable:%d\n",*ip);

[Link]

38/77

11/4/2015

CQuickGuide

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Addressofvarvariable:bffd8b3c
Addressstoredinipvariable:bffd8b3c
Valueof*ipvariable:20

NULLPointers
ItisalwaysagoodpracticetoassignaNULLvaluetoapointervariableincaseyoudonothaveanexact
[Link]
iscalledanullpointer.
[Link]
followingprogram
#include<stdio.h>
intmain(){
int*ptr=NULL;
printf("Thevalueofptris:%x\n",ptr);

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Thevalueofptris0

Inmostoftheoperatingsystems,programsarenotpermittedtoaccessmemoryataddress0because
[Link],thememoryaddress0hasspecial
[Link]
convention,ifapointercontainsthenullzerovalue,itisassumedtopointtonothing.
Tocheckforanullpointer,youcanusean'if'statementasfollows
if(ptr)/*succeedsifpisnotnull*/
if(!ptr)/*succeedsifpisnull*/

PointersinDetail
[Link]
importantpointerconceptsshouldbecleartoanyCprogrammer

[Link].

Concept&Description

[Link]

39/77

11/4/2015

CQuickGuide

Pointerarithmetic
Therearefourarithmeticoperatorsthatcanbeusedinpointers:++,,+,

Arrayofpointers
Youcandefinearraystoholdanumberofpointers.

Pointertopointer
Callowsyoutohavepointeronapointerandsoon.

PassingpointerstofunctionsinC
Passinganargumentbyreferenceorbyaddressenablethepassedargumenttobechanged
inthecallingfunctionbythecalledfunction.

ReturnpointerfromfunctionsinC
Callowsafunctiontoreturnapointertothelocalvariable,staticvariable,anddynamically
allocatedmemoryaswell.

CSTRINGS
Stringsareactuallyonedimensionalarrayofcharactersterminatedbyanullcharacter'\0'.Thusa
nullterminatedstringcontainsthecharactersthatcomprisethestringfollowedbyanull.
Thefollowingdeclarationandinitializationcreateastringconsistingoftheword"Hello".Toholdthe
nullcharacterattheendofthearray,thesizeofthecharacterarraycontainingthestringisonemore
thanthenumberofcharactersintheword"Hello."
chargreeting[6]={'H','e','l','l','o','\0'};

Ifyoufollowtheruleofarrayinitializationthenyoucanwritetheabovestatementasfollows
chargreeting[]="Hello";

FollowingisthememorypresentationoftheabovedefinedstringinC/C++

[Link]

40/77

11/4/2015

CQuickGuide

Actually,[Link]
automaticallyplacesthe'\0'[Link]
abovementionedstring
#include<stdio.h>
intmain(){
chargreeting[6]={'H','e','l','l','o','\0'};
printf("Greetingmessage:%s\n",greeting);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Greetingmessage:Hello

Csupportsawiderangeoffunctionsthatmanipulatenullterminatedstrings

S.N.
1

Function&Purpose
strcpys1, s2
Copiesstrings2intostrings1.

strcat s1, s2
Concatenatesstrings2ontotheendofstrings1.

strlens1
Returnsthelengthofstrings1.

[Link]

41/77

11/4/2015

CQuickGuide

strcmps1, s2
Returns0ifs1ands2arethesamelessthan0ifs1<s2greaterthan0ifs1>s2.

strchrs1, ch
Returnsapointertothefirstoccurrenceofcharacterchinstrings1.

strstrs1, s2
Returnsapointertothefirstoccurrenceofstrings2instrings1.

Thefollowingexampleusessomeoftheabovementionedfunctions
#include<stdio.h>
#include<string.h>
intmain(){
charstr1[12]="Hello";
charstr2[12]="World";
charstr3[12];
intlen;
/*copystr1intostr3*/
strcpy(str3,str1);
printf("strcpy(str3,str1):%s\n",str3);
/*concatenatesstr1andstr2*/
strcat(str1,str2);
printf("strcat(str1,str2):%s\n",str1);
/*totallenghthofstr1afterconcatenation*/
len=strlen(str1);
printf("strlen(str1):%d\n",len);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
strcpy(str3,str1):Hello
strcat(str1,str2):HelloWorld
strlen(str1):10

CSTRUCTURES

[Link]

42/77

11/4/2015

CQuickGuide

[Link]
structureisanotheruserdefineddatatypeavailableinCthatallowstocombinedataitemsof
differentkinds.
[Link].
Youmightwanttotrackthefollowingattributesabouteachbook
Title
Author
Subject
BookID

DefiningaStructure
Todefineastructure,[Link],
[Link]
struct[structuretag]{
memberdefinition;
memberdefinition;
...
memberdefinition;
}[oneormorestructurevariables];

Thestructuretagisoptionalandeachmemberdefinitionisanormalvariabledefinition,suchasinti
[Link]'sdefinition,beforethefinal
semicolon,[Link]
declaretheBookstructure
structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
}book;

AccessingStructureMembers
Toaccessanymemberofastructure,weusethememberaccessoperator . .Thememberaccess
operatoriscodedasaperiodbetweenthestructurevariablenameandthestructurememberthatwe
[Link]
exampleshowshowtouseastructureinaprogram
#include<stdio.h>
#include<string.h>

structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;

[Link]

43/77

11/4/2015

CQuickGuide

};

intmain(){
structBooksBook1;/*DeclareBook1oftypeBook*/
structBooksBook2;/*DeclareBook2oftypeBook*/

/*book1specification*/
strcpy([Link],"CProgramming");
strcpy([Link],"NuhaAli");
strcpy([Link],"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy([Link],"TelecomBilling");
strcpy([Link],"ZaraAli");
strcpy([Link],"TelecomBillingTutorial");
Book2.book_id=6495700;

/*printBook1info*/
printf("Book1title:%s\n",[Link]);
printf("Book1author:%s\n",[Link]);
printf("Book1subject:%s\n",[Link]);
printf("Book1book_id:%d\n",Book1.book_id);
/*printBook2info*/
printf("Book2title:%s\n",[Link]);
printf("Book2author:%s\n",[Link]);
printf("Book2subject:%s\n",[Link]);
printf("Book2book_id:%d\n",Book2.book_id);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Book1title:CProgramming
Book1author:NuhaAli
Book1subject:CProgrammingTutorial
Book1book_id:6495407
Book2title:TelecomBilling
Book2author:ZaraAli
Book2subject:TelecomBillingTutorial
Book2book_id:6495700

StructuresasFunctionArguments
Youcanpassastructureasafunctionargumentinthesamewayasyoupassanyothervariableor
pointer.
#include<stdio.h>
#include<string.h>

structBooks{
chartitle[50];
charauthor[50];

[Link]

44/77

11/4/2015

CQuickGuide

charsubject[100];
intbook_id;
};
/*functiondeclaration*/
voidprintBook(structBooksbook);
intmain(){
structBooksBook1;/*DeclareBook1oftypeBook*/
structBooksBook2;/*DeclareBook2oftypeBook*/

/*book1specification*/
strcpy([Link],"CProgramming");
strcpy([Link],"NuhaAli");
strcpy([Link],"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy([Link],"TelecomBilling");
strcpy([Link],"ZaraAli");
strcpy([Link],"TelecomBillingTutorial");
Book2.book_id=6495700;

/*printBook1info*/
printBook(Book1);
/*PrintBook2info*/
printBook(Book2);
return0;
}
voidprintBook(structBooksbook){
printf("Booktitle:%s\n",[Link]);
printf("Bookauthor:%s\n",[Link]);
printf("Booksubject:%s\n",[Link]);
printf("Bookbook_id:%d\n",book.book_id);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Booktitle:CProgramming
Bookauthor:NuhaAli
Booksubject:CProgrammingTutorial
Bookbook_id:6495407
Booktitle:TelecomBilling
Bookauthor:ZaraAli
Booksubject:TelecomBillingTutorial
Bookbook_id:6495700

PointerstoStructures
Youcandefinepointerstostructuresinthesamewayasyoudefinepointertoanyothervariable
structBooks*struct_pointer;

[Link]

45/77

11/4/2015

CQuickGuide

Now,[Link]
addressofastructurevariable,placethe'&'operatorbeforethestructure'snameasfollows
struct_pointer=&Book1;

Toaccessthemembersofastructureusingapointertothatstructure,youmustusetheoperatoras
follows
struct_pointer>title;

Letusrewritetheaboveexampleusingstructurepointer.
#include<stdio.h>
#include<string.h>

structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
};
/*functiondeclaration*/
voidprintBook(structBooks*book);
intmain(){
structBooksBook1;/*DeclareBook1oftypeBook*/
structBooksBook2;/*DeclareBook2oftypeBook*/

/*book1specification*/
strcpy([Link],"CProgramming");
strcpy([Link],"NuhaAli");
strcpy([Link],"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy([Link],"TelecomBilling");
strcpy([Link],"ZaraAli");
strcpy([Link],"TelecomBillingTutorial");
Book2.book_id=6495700;

/*printBook1infobypassingaddressofBook1*/
printBook(&Book1);
/*printBook2infobypassingaddressofBook2*/
printBook(&Book2);
return0;
}
voidprintBook(structBooks*book){
printf("Booktitle:%s\n",book>title);
printf("Bookauthor:%s\n",book>author);
printf("Booksubject:%s\n",book>subject);

[Link]

46/77

11/4/2015

CQuickGuide

printf("Bookbook_id:%d\n",book>book_id);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Booktitle:CProgramming
Bookauthor:NuhaAli
Booksubject:CProgrammingTutorial
Bookbook_id:6495407
Booktitle:TelecomBilling
Bookauthor:ZaraAli
Booksubject:TelecomBillingTutorial
Bookbook_id:6495700

BitFields
[Link]
[Link]
Packingseveralobjectsintoamachineword.e.g.1bitflagscanbecompacted.
Readingexternalfileformatsnonstandardfileformatscouldbereadin,e.g.,9bitintegers.
Callowsustodothisinastructuredefinitionbyputting:[Link]
structpacked_struct{
unsignedintf1:1;
unsignedintf2:1;
unsignedintf3:1;
unsignedintf4:1;
unsignedinttype:4;
unsignedintmy_int:9;
}pack;

Here,thepacked_structcontains6members:Four1bitflagsf1..f3,a4bittypeanda9bitmy_int.
Cautomaticallypackstheabovebitfieldsascompactlyaspossible,providedthatthemaximumlength
[Link],then
somecompilersmayallowmemoryoverlapforthefieldswhileotherswouldstorethenextfieldinthe
nextword.

CUNIONS
AunionisaspecialdatatypeavailableinCthatallowstostoredifferentdatatypesinthesame
[Link],butonlyonemembercancontaina
[Link]
multiplepurpose.

DefiningaUnion
Todefineaunion,youmustusetheunionstatementinthesamewayasyoudidwhiledefininga
[Link].
Theformatoftheunionstatementisasfollows

[Link]

47/77

11/4/2015

CQuickGuide

union[uniontag]{
memberdefinition;
memberdefinition;
...
memberdefinition;
}[oneormoreunionvariables];

Theuniontagisoptionalandeachmemberdefinitionisanormalvariabledefinition,suchasintior
[Link]'sdefinition,beforethefinal
semicolon,[Link]
defineauniontypenamedDatahavingthreemembersi,f,andstr
unionData{
inti;
floatf;
charstr[20];
}data;

Now,avariableofDatatypecanstoreaninteger,afloatingpointnumber,[Link]
meansasinglevariable,i.e.,samememorylocation,[Link]
useanybuiltinoruserdefineddatatypesinsideaunionbasedonyourrequirement.
[Link]
example,intheaboveexample,Datatypewilloccupy20bytesofmemoryspacebecausethisisthe
[Link]
memorysizeoccupiedbytheaboveunion
#include<stdio.h>
#include<string.h>

unionData{
inti;
floatf;
charstr[20];
};

intmain(){
unionDatadata;
printf("Memorysizeoccupiedbydata:%d\n",sizeof(data));
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Memorysizeoccupiedbydata:20

AccessingUnionMembers
Toaccessanymemberofaunion,weusethememberaccessoperator . .Thememberaccess
operatoriscodedasaperiodbetweentheunionvariablenameandtheunionmemberthatwewishto
[Link]

[Link]

48/77

11/4/2015

CQuickGuide

showshowtouseunionsinaprogram
#include<stdio.h>
#include<string.h>

unionData{
inti;
floatf;
charstr[20];
};

intmain(){
unionDatadata;
data.i=10;
data.f=220.5;
strcpy([Link],"CProgramming");
printf("data.i:%d\n",data.i);
printf("data.f:%f\n",data.f);
printf("[Link]:%s\n",[Link]);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
data.i:1917853763
data.f:4122360580327794860452759994368.000000
[Link]:CProgramming

Here,wecanseethatthevaluesofiandfmembersofuniongotcorruptedbecausethefinalvalue
assignedtothevariablehasoccupiedthememorylocationandthisisthereasonthatthevalueofstr
memberisgettingprintedverywell.
Nowlet'slookintothesameexampleonceagainwherewewilluseonevariableatatimewhichisthe
mainpurposeofhavingunions
#include<stdio.h>
#include<string.h>

unionData{
inti;
floatf;
charstr[20];
};

intmain(){
unionDatadata;
data.i=10;
printf("data.i:%d\n",data.i);

[Link]

49/77

11/4/2015

CQuickGuide

data.f=220.5;
printf("data.f:%f\n",data.f);

strcpy([Link],"CProgramming");
printf("[Link]:%s\n",[Link]);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
data.i:10
data.f:220.500000
[Link]:CProgramming

Here,allthemembersaregettingprintedverywellbecauseonememberisbeingusedatatime.

CBITFIELDS
SupposeyourCprogramcontainsanumberofTRUE/FALSEvariablesgroupedinastructurecalled
status,asfollows
struct{
unsignedintwidthValidated;
unsignedintheightValidated;
}status;

Thisstructurerequires8bytesofmemoryspacebutinactual,wearegoingtostoreeither0or1ineach
[Link]
situations.
Ifyouareusingsuchvariablesinsideastructurethenyoucandefinethewidthofavariablewhichtells
[Link],theabovestructure
canberewrittenasfollows
struct{
unsignedintwidthValidated:1;
unsignedintheightValidated:1;
}status;

Theabovestructurerequires4bytesofmemoryspaceforstatusvariable,butonly2bitswillbeusedto
storethevalues.
Ifyouwilluseupto32variableseachonewithawidthof1bit,thenalsothestatusstructurewilluse4
bytes.Howeverassoonasyouhave33variables,itwillallocatethenextslotofthememoryanditwill
[Link]
#include<stdio.h>
#include<string.h>
/*definesimplestructure*/
struct{
unsignedintwidthValidated;

[Link]

50/77

11/4/2015

CQuickGuide

unsignedintheightValidated;
}status1;
/*defineastructurewithbitfields*/
struct{
unsignedintwidthValidated:1;
unsignedintheightValidated:1;
}status2;

intmain(){
printf("Memorysizeoccupiedbystatus1:%d\n",sizeof(status1));
printf("Memorysizeoccupiedbystatus2:%d\n",sizeof(status2));
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Memorysizeoccupiedbystatus1:8
Memorysizeoccupiedbystatus2:4

BitFieldDeclaration
Thedeclarationofabitfieldhasthefollowingforminsideastructure
struct{
type[member_name]:width;
};

Thefollowingtabledescribesthevariableelementsofabitfield

Elements

Description

type

Anintegertypethatdetermineshowabitfield'[Link]
maybeint,signedint,orunsignedint.

member_name

Thenameofthebitfield.

width

[Link]
bitwidthofthespecifiedtype.

[Link]
singlebitforexample,ifyouneedavariabletostoreavaluefrom0to7,thenyoucandefineabitfield
withawidthof3bitsasfollows
struct{
unsignedintage:3;
}Age;

[Link]

51/77

11/4/2015

CQuickGuide

TheabovestructuredefinitioninstructstheCcompilerthattheagevariableisgoingtouseonly3bits
tostorethevalue.Ifyoutrytousemorethan3bits,[Link]
followingexample
#include<stdio.h>
#include<string.h>
struct{
unsignedintage:3;
}Age;
intmain(){
[Link]=4;
printf("Sizeof(Age):%d\n",sizeof(Age));
printf("[Link]:%d\n",[Link]);
[Link]=7;
printf("[Link]:%d\n",[Link]);
[Link]=8;
printf("[Link]:%d\n",[Link]);
return0;
}

Whentheabovecodeiscompileditwillcompilewithawarningandwhenexecuted,itproducesthe
followingresult
Sizeof(Age):4
[Link]
[Link]
[Link]

CTYPEDEF
TheCprogramminglanguageprovidesakeywordcalledtypedef,whichyoucanusetogiveatype,a
[Link]
typedefunsignedcharBYTE;

Afterthistypedefinition,theidentifierBYTEcanbeusedasanabbreviationforthetypeunsigned
char,forexample..
BYTEb1,b2;

Byconvention,uppercaselettersareusedforthesedefinitionstoremindtheuserthatthetypenameis
reallyasymbolicabbreviation,butyoucanuselowercase,asfollows
typedefunsignedcharbyte;

[Link],youcanuse
typedefwithstructuretodefineanewdatatypeandthenusethatdatatypetodefinestructure

[Link]

52/77

11/4/2015

CQuickGuide

variablesdirectlyasfollows
#include<stdio.h>
#include<string.h>

typedefstructBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
}Book;

intmain(){
Bookbook;

strcpy([Link],"CProgramming");
strcpy([Link],"NuhaAli");
strcpy([Link],"CProgrammingTutorial");
book.book_id=6495407;

printf("Booktitle:%s\n",[Link]);
printf("Bookauthor:%s\n",[Link]);
printf("Booksubject:%s\n",[Link]);
printf("Bookbook_id:%d\n",book.book_id);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Booktitle:CProgramming
Bookauthor:NuhaAli
Booksubject:CProgrammingTutorial
Bookbook_id:6495407

typedefvs#define
#defineisaCdirectivewhichisalsousedtodefinethealiasesforvariousdatatypessimilarto
typedefbutwiththefollowingdifferences
typedefislimitedtogivingsymbolicnamestotypesonlywhereas#definecanbeusedto
definealiasforvaluesaswell,q.,youcandefine1asONEetc.
typedefinterpretationisperformedbythecompilerwhereas#definestatementsare
processedbythepreprocessor.
Thefollowingexampleshowshowtouse#defineinaprogram
#include<stdio.h>

#defineTRUE1
#defineFALSE0

intmain(){

[Link]

53/77

11/4/2015

CQuickGuide

printf("ValueofTRUE:%d\n",TRUE);
printf("ValueofFALSE:%d\n",FALSE);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
ValueofTRUE:1
ValueofFALSE:0

CINPUT&OUTPUT
WhenwesayInput,[Link]
[Link]
inputandfeedittotheprogramasperrequirement.
WhenwesayOutput,itmeanstodisplaysomedataonscreen,printer,[Link]
providesasetofbuiltinfunctionstooutputthedataonthecomputerscreenaswellastosaveitintext
orbinaryfiles.

TheStandardFiles
[Link]
wayasfilesandthefollowingthreefilesareautomaticallyopenedwhenaprogramexecutestoprovide
accesstothekeyboardandscreen.

StandardFile

FilePointer

Device

Standardinput

stdin

Keyboard

Standardoutput

stdout

Screen

Standarderror

stderr

Yourscreen

[Link]
howtoreadvaluesfromthescreenandhowtoprinttheresultonthescreen.

ThegetcharandputcharFunctions
Theintgetcharvoid functionreadsthenextavailablecharacterfromthescreenandreturnsitasan
[Link]
youwanttoreadmorethanonecharacterfromthescreen.
Theintputcharintc functionputsthepassedcharacteronthescreenandreturnsthesamecharacter.
[Link]
[Link]
#include<stdio.h>
intmain(){

[Link]

54/77

11/4/2015

CQuickGuide

intc;
printf("Enteravalue:");
c=getchar();
printf("\nYouentered:");
putchar(c);
return0;
}

Whentheabovecodeiscompiledandexecuted,[Link]
textandpressenter,thentheprogramproceedsandreadsonlyasinglecharacteranddisplaysitas
follows
$./[Link]
Enteravalue:thisistest
Youentered:t

ThegetsandputsFunctions
Thechar*getschar s functionreadsalinefromstdinintothebufferpointedtobysuntileithera
terminatingnewlineorEOFEndof F ile .
Theintputsconstchar s functionwritesthestring's'and'a'trailingnewlinetostdout.
#include<stdio.h>
intmain(){
charstr[100];
printf("Enteravalue:");
gets(str);
printf("\nYouentered:");
puts(str);
return0;
}

Whentheabovecodeiscompiledandexecuted,[Link]
textandpressenter,thentheprogramproceedsandreadsthecompletelinetillend,anddisplaysitas
follows
$./[Link]
Enteravalue:thisistest
Youentered:Thisistest

ThescanfandprintfFunctions
Theintscanf constchar f ormat, . . . functionreadstheinputfromthestandardinputstreamstdin
andscansthatinputaccordingtotheformatprovided.
Theintprintf constchar f ormat, . . . functionwritestheoutputtothestandardoutputstream

[Link]

55/77

11/4/2015

CQuickGuide

stdoutandproducestheoutputaccordingtotheformatprovided.
Theformatcanbeasimpleconstantstring,butyoucanspecify%s,%d,%c,%f,etc.,toprintorread
strings,integer,[Link]
[Link]
conceptsbetter
#include<stdio.h>
intmain(){
charstr[100];
inti;
printf("Enteravalue:");
scanf("%s%d",str,&i);
printf("\nYouentered:%s%d",str,i);
return0;
}

Whentheabovecodeiscompiledandexecuted,[Link]
textandpressenter,thenprogramproceedsandreadstheinputanddisplaysitasfollows
$./[Link]
Enteravalue:seven7
Youentered:seven7

Here,itshouldbenotedthatscanfexpectsinputinthesameformatasyouprovided%sand%d,which
meansyouhavetoprovidevalidinputslike"stringinteger".Ifyouprovide"stringstring"or"integer
integer",[Link],whilereadingastring,scanfstopsreadingas
soonasitencountersaspace,so"thisistest"arethreestringsforscanf.

CFILEI/O
ThelastchapterexplainedthestandardinputandoutputdeviceshandledbyCprogramminglanguage.
ThischaptercoverhowCprogrammerscancreate,open,closetextorbinaryfilesfortheirdata
storage.
Afilerepresentsasequenceofbytes,[Link]
languageprovidesaccessonhighlevelfunctionsaswellaslowlevelOS levelcallstohandlefileonyour
[Link].

OpeningFiles
[Link]
objectofthetypeFILE,[Link]
prototypeofthisfunctioncallisasfollows
FILE*fopen(constchar*filename,constchar*mode);

Here,filenameisastringliteral,whichyouwillusetonameyourfile,andaccessmodecanhaveone
ofthefollowingvalues

[Link]

56/77

11/4/2015

CQuickGuide

Mode

Description

Opensanexistingtextfileforreadingpurpose.

[Link],[Link]
programwillstartwritingcontentfromthebeginningofthefile.

[Link],thenanewfileis
[Link].

r+

Opensatextfileforbothreadingandwriting.

w+

[Link]
exists,otherwisecreatesafileifitdoesnotexist.

a+

[Link]
readingwillstartfromthebeginningbutwritingcanonlybeappended.

Ifyouaregoingtohandlebinaryfiles,thenyouwillusefollowingaccessmodesinsteadoftheabove
mentionedones
"rb","wb","ab","rb+","r+b","wb+","w+b","ab+","a+b"

ClosingaFile
Tocloseafile,[Link]
intfclose(FILE*fp);

Thefclose functionreturnszeroonsuccess,[Link]
functionactuallyflushesanydatastillpendinginthebuffertothefile,closesthefile,andreleasesany
[Link].h.
TherearevariousfunctionsprovidedbyCstandardlibrarytoreadandwriteafile,characterby
character,orintheformofafixedlengthstring.

WritingaFile
Followingisthesimplestfunctiontowriteindividualcharacterstoastream
intfputc(intc,FILE*fp);

Thefunctionfputcwritesthecharactervalueoftheargumentctotheoutputstreamreferencedbyfp.
[Link]
followingfunctionstowriteanullterminatedstringtoastream
intfputs(constchar*s,FILE*fp);

[Link]

57/77

11/4/2015

CQuickGuide

[Link]
valueonsuccess,[Link]
F I LE f p, constchar f ormat, . . . [Link]
example.
Makesureyouhave/[Link],thenbeforeproceeding,youmustcreatethis
directoryonyourmachine.
#include<stdio.h>
main(){
FILE*fp;
fp=fopen("/tmp/[Link]","w+");
fprintf(fp,"Thisistestingforfprintf...\n");
fputs("Thisistestingforfputs...\n",fp);
fclose(fp);
}

Whentheabovecodeiscompiledandexecuted,[Link]/tmpdirectoryand
[Link].

ReadingaFile
Givenbelowisthesimplestfunctiontoreadasinglecharacterfromafile
intfgetc(FILE*fp);

[Link]
characterread,orincaseofanyerror,[Link]
fromastream
char*fgets(char*buf,intn,FILE*fp);

[Link]
readstringintothebufferbuf,appendinganullcharactertoterminatethestring.
Ifthisfunctionencountersanewlinecharacter'\n'ortheendofthefileEOFbeforetheyhavereadthe
maximumnumberofcharacters,thenitreturnsonlythecharactersreaduptothatpointincludingthe
[Link] F I LE f p, constchar f ormat, . . . functiontoread
stringsfromafile,butitstopsreadingafterencounteringthefirstspacecharacter.
#include<stdio.h>
main(){
FILE*fp;
charbuff[255];
fp=fopen("/tmp/[Link]","r");
fscanf(fp,"%s",buff);
printf("1:%s\n",buff);
fgets(buff,255,(FILE*)fp);

[Link]

58/77

11/4/2015

CQuickGuide

printf("2:%s\n",buff);

fgets(buff,255,(FILE*)fp);
printf("3:%s\n",buff);
fclose(fp);
}

Whentheabovecodeiscompiledandexecuted,itreadsthefilecreatedintheprevioussectionand
producesthefollowingresult
1:This
2:istestingforfprintf...
3:Thisistestingforfputs...

Let'[Link],fscanfreadjustThisbecauseafter
that,itencounteredaspace,secondcallisforfgetswhichreadstheremaininglinetillitencountered
[Link],thelastcallfgetsreadsthesecondlinecompletely.

BinaryI/OFunctions
Therearetwofunctions,thatcanbeusedforbinaryinputandoutput
size_tfread(void*ptr,size_tsize_of_elements,size_tnumber_of_elements,FILE
*a_file);

size_tfwrite(constvoid*ptr,size_tsize_of_elements,size_tnumber_of_elements,FILE
*a_file);

Bothofthesefunctionsshouldbeusedtoreadorwriteblocksofmemoriesusuallyarraysor
structures.

CPREPROCESSORS
TheCPreprocessorisnotapartofthecompiler,[Link]
simpleterms,aCPreprocessorisjustatextsubstitutiontoolanditinstructsthecompilertodo
[Link]'llrefertotheCPreprocessorasCPP.
Allpreprocessorcommandsbeginwithahashsymbol # .Itmustbethefirstnonblankcharacter,and
forreadability,[Link]
downalltheimportantpreprocessordirectives

Directive

Description

#define

Substitutesapreprocessormacro.

#include

Insertsaparticularheaderfromanotherfile.

#undef

Undefinesapreprocessormacro.

[Link]

59/77

11/4/2015

CQuickGuide

#ifdef

Returnstrueifthismacroisdefined.

#ifndef

Returnstrueifthismacroisnotdefined.

#if

Testsifacompiletimeconditionistrue.

#else

Thealternativefor#if.

#elif

#elseand#ifinonestatement.

#endif

Endspreprocessorconditional.

#error

Printserrormessageonstderr.

#pragma

Issuesspecialcommandstothecompiler,usingastandardizedmethod.

PreprocessorsExamples
Analyzethefollowingexamplestounderstandvariousdirectives.
#defineMAX_ARRAY_LENGTH20

ThisdirectivetellstheCPPtoreplaceinstancesofMAX_ARRAY_LENGTHwith20.Use#definefor
constantstoincreasereadability.
#include<stdio.h>
#include"myheader.h"

[Link]
[Link]
thecurrentsourcefile.
#undefFILE_SIZE
#defineFILE_SIZE42

IttellstheCPPtoundefineexistingFILE_SIZEanddefineitas42.
#ifndefMESSAGE
#defineMESSAGE"Youwish!"
#endif

IttellstheCPPtodefineMESSAGEonlyifMESSAGEisn'talreadydefined.
#ifdefDEBUG
/*Yourdebuggingstatementshere*/
#endif

[Link]
[Link],soyoucanturn

[Link]

60/77

11/4/2015

CQuickGuide

debuggingonandoffontheflyduringcompilation.

PredefinedMacros
[Link],the
predefinedmacrosshouldnotbedirectlymodified.

Macro

Description

__DATE__

Thecurrentdateasacharacterliteralin"MMMDDYYYY"format.

__TIME__

Thecurrenttimeasacharacterliteralin"HH:MM:SS"format.

__FILE__

Thiscontainsthecurrentfilenameasastringliteral.

__LINE__

Thiscontainsthecurrentlinenumberasadecimalconstant.

__STDC__

Definedas1whenthecompilercomplieswiththeANSIstandard.

Let'strythefollowingexample
#include<stdio.h>
main(){
printf("File:%s\n",__FILE__);
printf("Date:%s\n",__DATE__);
printf("Time:%s\n",__TIME__);
printf("Line:%d\n",__LINE__);
printf("ANSI:%d\n",__STDC__);
}

[Link],itproducesthefollowingresult
File:test.c
Date:Jun22012
Time:03:36:24
Line:8
ANSI:1

PreprocessorOperators
TheCpreprocessoroffersthefollowingoperatorstohelpcreatemacros

TheMacroContinuation(\)Operator
[Link](\)isusedtocontinuea
[Link]

[Link]

61/77

11/4/2015

CQuickGuide

#definemessage_for(a,b)\
printf(#a"and"#b":Weloveyou!\n")

TheStringize # Operator
Thestringizeornumbersignoperator '#' ,whenusedwithinamacrodefinition,convertsamacro
[Link]
[Link]
#include<stdio.h>
#definemessage_for(a,b)\
printf(#a"and"#b":Weloveyou!\n")
intmain(void){
message_for(Carole,Debra);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
CaroleandDebra:Weloveyou!

TheTokenPasting ## Operator
Thetokenpastingoperator ## [Link]
[Link]
#include<stdio.h>
#definetokenpaster(n)printf("token"#n"=%d",token##n)
intmain(void){
inttoken34=40;
tokenpaster(34);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
token34=40

Ithappenedsobecausethisexampleresultsinthefollowingactualoutputfromthepreprocessor
printf("token34=%d",token34);

Thisexampleshowstheconcatenationoftoken##nintotoken34andherewehaveusedbothstringize
andtokenpasting.

TheDefinedOperator

[Link]

62/77

11/4/2015

CQuickGuide

Thepreprocessordefinedoperatorisusedinconstantexpressionstodetermineifanidentifieris
definedusing#[Link],thevalueistruenon zero .Ifthesymbolis
notdefined,[Link]
#include<stdio.h>
#if!defined(MESSAGE)
#defineMESSAGE"Youwish!"
#endif
intmain(void){
printf("Hereisthemessage:%s\n",MESSAGE);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Hereisthemessage:Youwish!

ParameterizedMacros
OneofthepowerfulfunctionsoftheCPPistheabilitytosimulatefunctionsusingparameterized
[Link],wemighthavesomecodetosquareanumberasfollows
intsquare(intx){
returnx*x;
}

Wecanrewriteabovethecodeusingamacroasfollows
#definesquare(x)((x)*(x))

Macroswithargumentsmustbedefinedusingthe#[Link]
[Link]
[Link]
#include<stdio.h>
#defineMAX(x,y)((x)>(y)?(x):(y))
intmain(void){
printf("Maxbetween20and10is%d\n",MAX(10,20));
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Maxbetween20and10is20

CHEADERFILES
[Link]

[Link]

63/77

11/4/2015

CQuickGuide

[Link]:thefilesthatthe
programmerwritesandthefilesthatcomeswithyourcompiler.
YourequesttouseaheaderfileinyourprogrambyincludingitwiththeCpreprocessingdirective
#include,[Link],whichcomesalongwithyourcompiler.
Includingaheaderfileisequaltocopyingthecontentoftheheaderfilebutwedonotdoitbecauseit
willbeerrorproneanditisnotagoodideatocopythecontentofaheaderfileinthesourcefiles,
especiallyifwehavemultiplesourcefilesinaprogram.
AsimplepracticeinCorC++programsisthatwekeepalltheconstants,macros,systemwideglobal
variables,andfunctionprototypesintheheaderfilesandincludethatheaderfilewhereveritis
required.

IncludeSyntax
Boththeuserandthesystemheaderfilesareincludedusingthepreprocessingdirective#[Link]
hasthefollowingtwoforms
#include<file>

[Link]'file'inastandardlistofsystem
[Link].
#include"file"

[Link]'file'inthedirectory
[Link]
yoursourcecode.

IncludeOperation
The#includedirectiveworksbydirectingtheCpreprocessortoscanthespecifiedfileasinputbefore
[Link]
outputalreadygenerated,followedbytheoutputresultingfromtheincludedfile,followedbythe
outputthatcomesfromthetextafterthe#[Link],ifyouhaveaheaderfile
[Link]
char*test(void);

[Link],likethis
intx;
#include"header.h"
intmain(void){
puts(test());
}

[Link].
intx;
char*test(void);

[Link]

64/77

11/4/2015

CQuickGuide

intmain(void){
puts(test());
}

OnceOnlyHeaders
Ifaheaderfilehappenstobeincludedtwice,thecompilerwillprocessitscontentstwiceanditwill
[Link]
conditional,likethis
#ifndefHEADER_FILE
#defineHEADER_FILE
theentireheaderfilefile
#endif

Thisconstructiscommonlyknownasawrapper#[Link],the
conditionalwillbefalse,becauseHEADER_FILEisdefined.Thepreprocessorwillskipovertheentire
contentsofthefile,andthecompilerwillnotseeittwice.

ComputedIncludes
Sometimesitisnecessarytoselectoneoftheseveraldifferentheaderfilestobeincludedintoyour
[Link],theymightspecifyconfigurationparameterstobeusedondifferentsortsof
[Link]
#ifSYSTEM_1
#include"system_1.h"
#elifSYSTEM_2
#include"system_2.h"
#elifSYSTEM_3
...
#endif

Butasitgrows,itbecomestedious,insteadthepreprocessorofferstheabilitytouseamacroforthe
[Link]
argumentof#include,yousimplyputamacronamethere
#defineSYSTEM_H"system_1.h"
...
#includeSYSTEM_H

SYSTEM_Hwillbeexpanded,andthepreprocessorwilllookforsystem_1.hasifthe#includehad
beenwrittenthatwayoriginally.SYSTEM_HcouldbedefinedbyyourMakefilewithaDoption.

CTYPECASTING
[Link],ifyou
wanttostorea'long'valueintoasimpleintegerthenyoucantypecast'long'to'int'.Youcanconvertthe
valuesfromonetypetoanotherexplicitlyusingthecastoperatorasfollows

[Link]

65/77

11/4/2015

CQuickGuide

(type_name)expression

Considerthefollowingexamplewherethecastoperatorcausesthedivisionofoneintegervariableby
anothertobeperformedasafloatingpointoperation
#include<stdio.h>
main(){
intsum=17,count=5;
doublemean;
mean=(double)sum/count;
printf("Valueofmean:%f\n",mean);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Valueofmean:3.400000

Itshouldbenotedherethatthecastoperatorhasprecedenceoverdivision,sothevalueofsumisfirst
convertedtotypedoubleandfinallyitgetsdividedbycountyieldingadoublevalue.
Typeconversionscanbeimplicitwhichisperformedbythecompilerautomatically,oritcanbe
[Link]
tousethecastoperatorwhenevertypeconversionsarenecessary.

IntegerPromotion
Integerpromotionistheprocessbywhichvaluesofintegertype"smaller"thanintorunsignedint
[Link]
integer
#include<stdio.h>
main(){
inti=17;
charc='c';/*asciivalueis99*/
intsum;
sum=i+c;
printf("Valueofsum:%d\n",sum);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Valueofsum:116

Here,thevalueofsumis116becausethecompilerisdoingintegerpromotionandconvertingthevalue
of'c'toASCIIbeforeperformingtheactualadditionoperation.

[Link]

66/77

11/4/2015

CQuickGuide

UsualArithmeticConversion
Theusualarithmeticconversionsareimplicitlyperformedtocasttheirvaluestoacommontype.
Thecompilerfirstperformsintegerpromotioniftheoperandsstillhavedifferenttypes,thentheyare
convertedtothetypethatappearshighestinthefollowinghierarchy

Theusualarithmeticconversionsarenotperformedfortheassignmentoperators,norforthelogical
operators&&and||.Letustakethefollowingexampletounderstandtheconcept
#include<stdio.h>
main(){
inti=17;
charc='c';/*asciivalueis99*/
floatsum;
sum=i+c;
printf("Valueofsum:%f\n",sum);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult

[Link]

67/77

11/4/2015

CQuickGuide

Valueofsum:116.000000

Here,itissimpletounderstandthatfirstcgetsconvertedtointeger,butasthefinalvalueisdouble,
usualarithmeticconversionappliesandthecompilerconvertsiandcinto'float'andaddsthemyielding
a'float'result.

CERRORHANDLING
Assuch,Cprogrammingdoesnotprovidedirectsupportforerrorhandlingbutbeingasystem
programminglanguage,[Link]
[Link]
[Link]
codesdefinedin<error.h>headerfile.
SoaCprogrammercancheckthereturnedvaluesandcantakeappropriateactiondependingonthe
[Link],toseterrnoto0atthetimeofinitializingaprogram.Avalueof0
indicatesthatthereisnoerrorintheprogram.

errno,[Link]
TheCprogramminglanguageprovidesperrorandstrerrorfunctionswhichcanbeusedtodisplaythe
textmessageassociatedwitherrno.
Theperrorfunctiondisplaysthestringyoupasstoit,followedbyacolon,aspace,andthenthe
textualrepresentationofthecurrenterrnovalue.
Thestrerrorfunction,whichreturnsapointertothetextualrepresentationofthecurrent
errnovalue.
Let'[Link]'musingboth
thefunctionstoshowtheusage,[Link]
importantpointtonoteisthatyoushouldusestderrfilestreamtooutputalltheerrors.
#include<stdio.h>
#include<errno.h>
#include<string.h>
externinterrno;
intmain(){
FILE*pf;
interrnum;
pf=fopen("[Link]","rb");

if(pf==NULL){

errnum=errno;
fprintf(stderr,"Valueoferrno:%d\n",errno);
perror("Errorprintedbyperror");
fprintf(stderr,"Erroropeningfile:%s\n",strerror(errnum));
}
else{

[Link]

68/77

11/4/2015

CQuickGuide

fclose(pf);
}

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Valueoferrno:2
Errorprintedbyperror:Nosuchfileordirectory
Erroropeningfile:Nosuchfileordirectory

DividebyZeroErrors
Itisacommonproblemthatatthetimeofdividinganynumber,programmersdonotcheckifadivisor
iszeroandfinallyitcreatesaruntimeerror.
Thecodebelowfixesthisbycheckingifthedivisoriszerobeforedividing
#include<stdio.h>
#include<stdlib.h>
main(){
intdividend=20;
intdivisor=0;
intquotient;

if(divisor==0){
fprintf(stderr,"Divisionbyzero!Exiting...\n");
exit(1);
}

quotient=dividend/divisor;
fprintf(stderr,"Valueofquotient:%d\n",quotient);
exit(0);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Divisionbyzero!Exiting...

ProgramExitStatus
ItisacommonpracticetoexitwithavalueofEXIT_SUCCESSincaseofprogramcomingoutaftera
[Link],EXIT_SUCCESSisamacroanditisdefinedas0.
Ifyouhaveanerrorconditioninyourprogramandyouarecomingoutthenyoushouldexitwitha
statusEXIT_FAILUREwhichisdefinedas1.Solet'swriteaboveprogramasfollows
#include<stdio.h>
#include<stdlib.h>

[Link]

69/77

11/4/2015

CQuickGuide

main(){
intdividend=20;
intdivisor=5;
intquotient;

if(divisor==0){
fprintf(stderr,"Divisionbyzero!Exiting...\n");
exit(EXIT_FAILURE);
}

quotient=dividend/divisor;
fprintf(stderr,"Valueofquotient:%d\n",quotient);
exit(EXIT_SUCCESS);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Valueofquotient:4

CRECURSION
[Link],ifa
programallowsyoutocallafunctioninsidethesamefunction,thenitiscalledarecursivecallofthe
function.
voidrecursion(){
recursion();/*functioncallsitself*/
}
intmain(){
recursion();
}

TheCprogramminglanguagesupportsrecursion,i.e.,[Link]
recursion,programmersneedtobecarefultodefineanexitconditionfromthefunction,otherwiseit
willgointoaninfiniteloop.
Recursivefunctionsareveryusefultosolvemanymathematicalproblems,suchascalculatingthe
factorialofanumber,generatingFibonacciseries,etc.

NumberFactorial
Thefollowingexamplecalculatesthefactorialofagivennumberusingarecursivefunction
#include<stdio.h>
intfactorial(unsignedinti){
if(i<=1){
return1;
}
returni*factorial(i1);

[Link]

70/77

11/4/2015

CQuickGuide

}
intmain(){
inti=15;
printf("Factorialof%dis%d\n",i,factorial(i));
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Factorialof15is2004310016

FibonacciSeries
ThefollowingexamplegeneratestheFibonacciseriesforagivennumberusingarecursivefunction
#include<stdio.h>
intfibonaci(inti){
if(i==0){
return0;
}

if(i==1){
return1;
}
returnfibonaci(i1)+fibonaci(i2);
}
intmain(){
inti;

for(i=0;i<10;i++){
printf("%d\t%n",fibonaci(i));
}

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
0

13

21

34

CVARIABLEARGUMENTS
Sometimes,youmaycomeacrossasituation,whenyouwanttohaveafunction,whichcantakevariable
numberofarguments,i.e.,parameters,[Link]
programminglanguageprovidesasolutionforthissituationandyouareallowedtodefineafunction
[Link]
showsthedefinitionofsuchafunction.
intfunc(int,...){

[Link]

71/77

11/4/2015

CQuickGuide

.
.
.
}
intmain(){
func(1,2,3);
func(1,2,3,4);
}

Itshouldbenotedthatthefunctionfunchasitslastargumentasellipses,[Link](...)andthe
onejustbeforetheellipsesisalwaysanintwhichwillrepresentthetotalnumbervariablearguments
[Link],[Link]
functionsandmacrostoimplementthefunctionalityofvariableargumentsandfollowthegivensteps
Defineafunctionwithitslastparameterasellipsesandtheonejustbeforetheellipsesisalways
anintwhichwillrepresentthenumberofarguments.
Createava_listtypevariableinthefunctiondefinition.[Link]
file.
Useintparameterandva_startmacrotoinitializetheva_listvariabletoanargumentlist.The
macrova_startisdefinedinstdarg.hheaderfile.
Useva_argmacroandva_listvariabletoaccesseachiteminargumentlist.
Useamacrova_endtocleanupthememoryassignedtova_listvariable.
Nowletusfollowtheabovestepsandwritedownasimplefunctionwhichcantakethevariablenumber
ofparametersandreturntheiraverage
#include<stdio.h>
#include<stdarg.h>
doubleaverage(intnum,...){
va_listvalist;
doublesum=0.0;
inti;
/*initializevalistfornumnumberofarguments*/
va_start(valist,num);
/*accessalltheargumentsassignedtovalist*/
for(i=0;i<num;i++){
sum+=va_arg(valist,int);
}

/*cleanmemoryreservedforvalist*/
va_end(valist);
returnsum/num;
}
intmain(){
printf("Averageof2,3,4,5=%f\n",average(4,2,3,4,5));

[Link]

72/77

11/4/2015

CQuickGuide

printf("Averageof5,10,15=%f\n",average(3,5,10,15));
}

Whentheabovecodeiscompiledandexecuted,[Link]
thefunctionaveragehasbeencalledtwiceandeachtimethefirstargumentrepresentsthetotal
[Link]
arguments.
Averageof2,3,4,5=3.500000
Averageof5,10,15=10.000000

CMEMORYMANAGEMENT
[Link]
[Link]
<stdlib.h>headerfile.

S.N.
1

Function&Description
void*callocintnum, intsize
Thisfunctionallocatesanarrayofnumelementseachofwhichsizeinbyteswillbesize.

voidfreevoid address
Thisfunctionreleasesablockofmemoryblockspecifiedbyaddress.

void*mallocintnum
Thisfunctionallocatesanarrayofnumbytesandleavetheminitialized.

void*reallocvoid address, intnewsize


Thisfunctionreallocatesmemoryextendingituptonewsize.

AllocatingMemoryDynamically
Whileprogramming,ifyouareawareofthesizeofanarray,thenitiseasyandyoucandefineitasan
[Link],tostoreanameofanyperson,itcangouptoamaximumof100characters,soyou
candefinesomethingasfollows
charname[100];

[Link]

73/77

11/4/2015

CQuickGuide

Butnowletusconsiderasituationwhereyouhavenoideaaboutthelengthofthetextyouneedto
store,forexample,[Link]
pointertocharacterwithoutdefininghowmuchmemoryisrequiredandlater,basedonrequirement,
wecanallocatememoryasshowninthebelowexample
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
intmain(){
charname[100];
char*description;
strcpy(name,"ZaraAli");
/*allocatememorydynamically*/
description=malloc(200*sizeof(char));

if(description==NULL){
fprintf(stderr,"Errorunabletoallocaterequiredmemory\n");
}
else{
strcpy(description,"ZaraaliaDPSstudentinclass10th");
}

printf("Name=%s\n",name);
printf("Description:%s\n",description);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult.
Name=ZaraAli
Description:ZaraaliaDPSstudentinclass10th

Sameprogramcanbewrittenusingcalloconlythingisyouneedtoreplacemallocwithcallocas
follows
calloc(200,sizeof(char));

Soyouhavecompletecontrolandyoucanpassanysizevaluewhileallocatingmemory,unlikearrays
whereoncethesizedefined,youcannotchangeit.

ResizingandReleasingMemory
Whenyourprogramcomesout,operatingsystemautomaticallyreleaseallthememoryallocatedby
yourprogrambutasagoodpracticewhenyouarenotinneedofmemoryanymorethenyoushould
releasethatmemorybycallingthefunctionfree.
Alternatively,youcanincreaseordecreasethesizeofanallocatedmemoryblockbycallingthefunction
[Link]
#include<stdio.h>
#include<stdlib.h>

[Link]

74/77

11/4/2015

CQuickGuide

#include<string.h>
intmain(){
charname[100];
char*description;
strcpy(name,"ZaraAli");
/*allocatememorydynamically*/
description=malloc(30*sizeof(char));

if(description==NULL){
fprintf(stderr,"Errorunabletoallocaterequiredmemory\n");
}
else{
strcpy(description,"ZaraaliaDPSstudent.");
}

/*supposeyouwanttostorebiggerdescription*/
description=realloc(description,100*sizeof(char));

if(description==NULL){
fprintf(stderr,"Errorunabletoallocaterequiredmemory\n");
}
else{
strcat(description,"Sheisinclass10th");
}

printf("Name=%s\n",name);
printf("Description:%s\n",description);
/*releasememoryusingfree()function*/
free(description);
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult.
Name=ZaraAli
Description:ZaraaliaDPSstudent.Sheisinclass10th

Youcantrytheaboveexamplewithoutreallocatingextramemory,andstrcatfunctionwillgivean
errorduetolackofavailablememoryindescription.

CCOMMANDLINEARGUMENTS
ItispossibletopasssomevaluesfromthecommandlinetoyourCprogramswhentheyareexecuted.
Thesevaluesarecalledcommandlineargumentsandmanytimestheyareimportantforyour
programespeciallywhenyouwanttocontrolyourprogramfromoutsideinsteadofhardcodingthose
valuesinsidethecode.
Thecommandlineargumentsarehandledusingmainfunctionargumentswhereargcreferstothe
numberofargumentspassed,andargv[]isapointerarraywhichpointstoeachargumentpassedto
[Link]
commandlineandtakeactionaccordingly

[Link]

75/77

11/4/2015

CQuickGuide

#include<stdio.h>
intmain(intargc,char*argv[]){
if(argc==2){
printf("Theargumentsuppliedis%s\n",argv[1]);
}
elseif(argc>2){
printf("Toomanyargumentssupplied.\n");
}
else{
printf("Oneargumentexpected.\n");
}
}

Whentheabovecodeiscompiledandexecutedwithsingleargument,itproducesthefollowingresult.
$./[Link]
Theargumentsuppliedistesting

Whentheabovecodeiscompiledandexecutedwithatwoarguments,itproducesthefollowingresult.
$./a.outtesting1testing2
Toomanyargumentssupplied.

Whentheabovecodeiscompiledandexecutedwithoutpassinganyargument,itproducesthefollowing
result.
$./[Link]
Oneargumentexpected

Itshouldbenotedthatargv[0]holdsthenameoftheprogramitselfandargv[1]isapointertothe
firstcommandlineargumentsupplied,and*argv[n][Link],
argcwillbeone,andifyoupassoneargumentthenargcissetat2.
Youpassallthecommandlineargumentsseparatedbyaspace,butifargumentitselfhasaspacethen
youcanpasssuchargumentsbyputtingtheminsidedoublequotes""orsinglequotes''.Letusrewrite
aboveexampleonceagainwherewewillprintprogramnameandwealsopassacommandline
argumentbyputtinginsidedoublequotes
#include<stdio.h>
intmain(intargc,char*argv[]){
printf("Programname%s\n",argv[0]);

if(argc==2){
printf("Theargumentsuppliedis%s\n",argv[1]);
}
elseif(argc>2){
printf("Toomanyargumentssupplied.\n");
}
else{
printf("Oneargumentexpected.\n");

[Link]

76/77

11/4/2015

CQuickGuide

}
}

Whentheabovecodeiscompiledandexecutedwithasingleargumentseparatedbyspacebutinside
doublequotes,itproducesthefollowingresult.
$./[Link]"testing1testing2"
Progranmname./[Link]
Theargumentsuppliedistesting1testing2

[Link]

77/77

You might also like