Sei sulla pagina 1di 77

11/4/2015

CQuickGuide

CQUICKGUIDE
http://www.tutorialspoint.com/cprogramming/c_quick_guide.htm

Copyrighttutorialspoint.com

CLANGUAGEOVERVIEW
Cisageneralpurpose,highlevellanguagethatwasoriginallydevelopedbyDennisM.Ritchieto
developtheUNIXoperatingsystematBellLabs.CwasoriginallyfirstimplementedontheDECPDP11
computerin1972.
In1978,BrianKernighanandDennisRitchieproducedthefirstpubliclyavailabledescriptionofC,now
knownastheK&Rstandard.
TheUNIXoperatingsystem,theCcompiler,andessentiallyallUNIXapplicationprogramshavebeen
writteninC.Chasnowbecomeawidelyusedprofessionallanguageforvariousreasons
Easytolearn
Structuredlanguage
Itproducesefficientprograms
Itcanhandlelowlevelactivities
Itcanbecompiledonavarietyofcomputerplatforms

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

WhyuseC?
Cwasinitiallyusedforsystemdevelopmentwork,particularlytheprogramsthatmakeupthe
operatingsystem.Cwasadoptedasasystemdevelopmentlanguagebecauseitproducescodethatruns
nearlyasfastasthecodewritteninassemblylanguage.SomeexamplesoftheuseofCmightbe
OperatingSystems
LanguageCompilers
Assemblers
TextEditors
PrintSpoolers

http://www.tutorialspoint.com/cgibin/printpage.cgi

1/77

11/4/2015

CQuickGuide

NetworkDrivers
ModernPrograms
Databases
LanguageInterpreters
Utilities

CPrograms
ACprogramcanvaryfrom3linestomillionsoflinesanditshouldbewrittenintooneormoretext
fileswithextension".c"forexample,hello.c.Youcanuse"vi","vim"oranyothertexteditortowrite
yourCprogramintoafile.
Thistutorialassumesthatyouknowhowtoeditatextfileandhowtowritesourcecodeinsidea
programfile.

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

return0;
}

Formostoftheexamplesgiveninthistutorial,youwillfindaTryitoptioninour
websitecodesectionsatthetoprightcornerthatwilltakeyoutotheonlinecompiler.
Sojustmakeuseofitandenjoyyourlearning.

LocalEnvironmentSetup
IfyouwanttosetupyourenvironmentforCprogramminglanguage,youneedthefollowingtwo
softwaretoolsavailableonyourcomputer,a TextEditorandb TheCCompiler.

TextEditor
Thiswillbeusedtotypeyourprogram.ExamplesoffewaeditorsincludeWindowsNotepad,OSEdit

http://www.tutorialspoint.com/cgibin/printpage.cgi

2/77

11/4/2015

CQuickGuide

command,Brief,Epsilon,EMACS,andvimorvi.
Thenameandversionoftexteditorscanvaryondifferentoperatingsystems.Forexample,Notepad
willbeusedonWindows,andvimorvicanbeusedonwindowsaswellasonLinuxorUNIX.
Thefilesyoucreatewithyoureditorarecalledthesourcefilesandtheycontaintheprogramsource
codes.ThesourcefilesforCprogramsaretypicallynamedwiththeextension".c".
Beforestartingyourprogramming,makesureyouhaveonetexteditorinplaceandyouhaveenough
experiencetowriteacomputerprogram,saveitinafile,compileitandfinallyexecuteit.

TheCCompiler
Thesourcecodewritteninsourcefileisthehumanreadablesourceforyourprogram.Itneedstobe
"compiled",intomachinelanguagesothatyourCPUcanactuallyexecutetheprogramasperthe
instructionsgiven.
Thecompilercompilesthesourcecodesintofinalexecutableprograms.Themostfrequentlyusedand
freeavailablecompileristheGNUC/C++compiler,otherwiseyoucanhavecompilerseitherfromHP
orSolarisifyouhavetherespectiveoperatingsystems.
ThefollowingsectionexplainshowtoinstallGNUC/C++compileronvariousOS.Wekeepmentioning
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
http://gcc.gnu.org/install/
ThistutorialhasbeenwrittenbasedonLinuxandallthegivenexampleshavebeencompiledonthe
CentOSflavoroftheLinuxsystem.

InstallationonMacOS
IfyouuseMacOSX,theeasiestwaytoobtainGCCistodownloadtheXcodedevelopmentenvironment
fromApple'swebsiteandfollowthesimpleinstallationinstructions.OnceyouhaveXcodesetup,you
willbeabletouseGNUcompilerforC/C++.
Xcodeiscurrentlyavailableatdeveloper.apple.com/technologies/tools/.

InstallationonWindows

http://www.tutorialspoint.com/cgibin/printpage.cgi

3/77

11/4/2015

CQuickGuide

ToinstallGCConWindows,youneedtoinstallMinGW.ToinstallMinGW,gototheMinGW
homepage,www.mingw.org,andfollowthelinktotheMinGWdownloadpage.Downloadthelatest
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
compilertoincludestdio.hfilebeforegoingtoactualcompilation.
Thenextlineintmainisthemainfunctionwheretheprogramexecutionbegins.
Thenextline/*...*/willbeignoredbythecompilerandithasbeenputtoaddadditional
commentsintheprogram.Sosuchlinesarecalledcommentsintheprogram.
Thenextlineprintf . . . isanotherfunctionavailableinCwhichcausesthemessage"Hello,
World!"tobedisplayedonthescreen.

http://www.tutorialspoint.com/cgibin/printpage.cgi

4/77

11/4/2015

CQuickGuide

Thenextlinereturn0terminatesthemainfunctionandreturnsthevalue0.

CompileandExecuteCProgram
Letusseehowtosavethesourcecodeinafile,andhowtocompileandrunit.Followingarethesimple
steps
Openatexteditorandaddtheabovementionedcode.
Savethefileashello.c
Openacommandpromptandgotothedirectorywhereyouhavesavedthefile.
Typegcchello.candpressentertocompileyourcode.
Iftherearenoerrorsinyourcode,thecommandpromptwilltakeyoutothenextlineandwould
generatea.outexecutablefile.
Now,typea.outtoexecuteyourprogram.
Youwillseetheoutput"HelloWorld"printedonthescreen.
$gcchello.c
$./a.out
Hello,World!

Makesurethegcccompilerisinyourpathandthatyouarerunningitinthedirectorycontainingthe
sourcefilehello.c.

CBASICSYNTAX
YouhaveseenthebasicstructureofaCprogram,soitwillbeeasytounderstandotherbasicbuilding
blocksoftheCprogramminglanguage.

TokensinC
ACprogramconsistsofvarioustokensandatokeniseitherakeyword,anidentifier,aconstant,a
stringliteral,orasymbol.Forexample,thefollowingCstatementconsistsoffivetokens
printf("Hello,World!\n");

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

Semicolons
InaCprogram,thesemicolonisastatementterminator.Thatis,eachindividualstatementmustbe
endedwithasemicolon.Itindicatestheendofonelogicalentity.

http://www.tutorialspoint.com/cgibin/printpage.cgi

5/77

11/4/2015

CQuickGuide

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

Comments
CommentsarelikehelpingtextinyourCprogramandtheyareignoredbythecompiler.Theystartwith
/*andterminatewiththecharacters*/asshownbelow
/*myfirstprograminC*/

Youcannothavecommentswithincommentsandtheydonotoccurwithinastringorcharacterliterals.

Identifiers
ACidentifierisanameusedtoidentifyavariable,function,oranyotheruserdefineditem.An
identifierstartswithaletterAtoZ,atoz,oranunderscore'_'followedbyzeroormoreletters,
underscores,anddigits0to9 .
Cdoesnotallowpunctuationcharacterssuchas@,$,and%withinidentifiers.Cisacasesensitive
programminglanguage.Thus,ManpowerandmanpoweraretwodifferentidentifiersinC.Hereare
someexamplesofacceptableidentifiers
mohdzaraabcmove_namea_123
myname50_tempja23b9retVal

Keywords
ThefollowinglistshowsthereservedwordsinC.Thesereservedwordsmaynotbeusedasconstantsor
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

http://www.tutorialspoint.com/cgibin/printpage.cgi

6/77

11/4/2015

CQuickGuide

WhitespaceinC
Alinecontainingonlywhitespace,possiblywithacomment,isknownasablankline,andaCcompiler
totallyignoresit.
WhitespaceisthetermusedinCtodescribeblanks,tabs,newlinecharactersandcomments.
Whitespaceseparatesonepartofastatementfromanotherandenablesthecompilertoidentifywhere
oneelementinastatement,suchasint,endsandthenextelementbegins.Therefore,inthefollowing
statement
intage;

theremustbeatleastonewhitespacecharacterusuallyaspace betweenintandageforthecompilerto
beabletodistinguishthem.Ontheotherhand,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.

http://www.tutorialspoint.com/cgibin/printpage.cgi

7/77

11/4/2015

CQuickGuide

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

Thearraytypesandstructuretypesarereferredcollectivelyastheaggregatetypes.Thetypeofa
functionspecifiesthetypeofthefunction'sreturnvalue.Wewillseethebasictypesinthefollowing
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 typeyieldsthestoragesizeoftheobjectortypeinbytes.Givenbelowisan
exampletogetthesizeofinttypeonanymachine
#include<stdio.h>
#include<limits.h>
intmain(){
printf("Storagesizeforint:%d\n",sizeof(int));

return0;

http://www.tutorialspoint.com/cgibin/printpage.cgi

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

Theheaderfilefloat.hdefinesmacrosthatallowyoutousethesevaluesandotherdetailsaboutthe
binaryrepresentationofrealnumbersinyourprograms.Thefollowingexampleprintsthestorage
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
Thevoidtypespecifiesthatnovalueisavailable.Itisusedinthreekindsofsituations

S.N.

http://www.tutorialspoint.com/cgibin/printpage.cgi

Types&Description

9/77

11/4/2015

CQuickGuide

Functionreturnsasvoid
TherearevariousfunctionsinCwhichdonotreturnanyvalueoryoucansaytheyreturn
void.Afunctionwithnoreturnvaluehasthereturntypeasvoid.Forexample,voidexit
intstatus

Functionargumentsasvoid
TherearevariousfunctionsinCwhichdonotacceptanyparameter.Afunctionwithno
parametercanacceptavoid.Forexample,intrandvoid

Pointerstovoid
Apointeroftypevoid*representstheaddressofanobject,butnotitstype.Forexample,a
memoryallocationfunctionvoid*mallocsize sizereturnsapointertovoidwhichcanbe
castedtoanydatatype.
t

CVARIABLES
Avariableisnothingbutanamegiventoastorageareathatourprogramscanmanipulate.Each
variableinChasaspecifictype,whichdeterminesthesizeandlayoutofthevariable'smemorythe
rangeofvaluesthatcanbestoredwithinthatmemoryandthesetofoperationsthatcanbeappliedto
thevariable.
Thenameofavariablecanbecomposedofletters,digits,andtheunderscorecharacter.Itmustbegin
witheitheraletteroranunderscore.UpperandlowercaselettersaredistinctbecauseCiscase
sensitive.Basedonthebasictypesexplainedinthepreviouschapter,therewillbethefollowingbasic
variabletypes

Type

Description

char

Typicallyasingleoctetonebyte .Thisisanintegertype.

int

Themostnaturalsizeofintegerforthemachine.

float

Asingleprecisionfloatingpointvalue.

double

Adoubleprecisionfloatingpointvalue.

void

Representstheabsenceoftype.

http://www.tutorialspoint.com/cgibin/printpage.cgi

10/77

11/4/2015

CQuickGuide

Cprogramminglanguagealsoallowstodefinevariousothertypesofvariables,whichwewillcoverin
subsequentchapterslikeEnumeration,Pointer,Array,Structure,Union,etc.Forthischapter,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.
Variablescanbeinitializedassignedaninitialvalueintheirdeclaration.Theinitializerconsistsofan
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
detailaboutthevariable.Avariabledeclarationhasitsmeaningatthetimeofcompilationonly,the
compilerneedsactualvariabledeclarationatthetimeoflinkingtheprogram.
Avariabledeclarationisusefulwhenyouareusingmultiplefilesandyoudefineyourvariableinoneof
thefileswhichwillbeavailableatthetimeoflinkingoftheprogram.Youwillusethekeywordextern
todeclareavariableatanyplace.ThoughyoucandeclareavariablemultipletimesinyourCprogram,
itcanbedefinedonlyonceinafile,afunction,orablockofcode.

Example

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
declarationanditsactualdefinitioncanbegivenanywhereelse.Forexample
//functiondeclaration
intfunc();
intmain(){
//functioncall
inti=func();
}
//functiondefinition
intfunc(){
return0;
}

LvaluesandRvaluesinC
TherearetwokindsofexpressionsinC

http://www.tutorialspoint.com/cgibin/printpage.cgi

12/77

11/4/2015

CQuickGuide

lvalueExpressionsthatrefertoamemorylocationarecalled"lvalue"expressions.Anlvalue
mayappearaseitherthelefthandorrighthandsideofanassignment.
rvalueThetermrvaluereferstoadatavaluethatisstoredatsomeaddressinmemory.An
rvalueisanexpressionthatcannothaveavalueassignedtoitwhichmeansanrvaluemayappear
ontherighthandsidebutnotonthelefthandsideofanassignment.
Variablesarelvaluesandsotheymayappearonthelefthandsideofanassignment.Numericliterals
arervaluesandsotheymaynotbeassignedandcannotappearonthelefthandside.Takealookatthe
followingvalidandinvalidstatements
intg=20;//validstatement
10=20;//invalidstatement;wouldgeneratecompiletimeerror

CCONSTANTS&LITERALS
Constantsrefertofixedvaluesthattheprogrammaynotalterduringitsexecution.Thesefixedvalues
arealsocalledliterals.
Constantscanbeofanyofthebasicdatatypeslikeanintegerconstant,afloatingconstant,acharacter
constant,orastringliteral.Thereareenumerationconstantsaswell.
Constantsaretreatedjustlikeregularvariablesexceptthattheirvaluescannotbemodifiedaftertheir
definition.

IntegerLiterals
Anintegerliteralcanbeadecimal,octal,orhexadecimalconstant.Aprefixspecifiesthebaseorradix:
0xor0Xforhexadecimal,0foroctal,andnothingfordecimal.
AnintegerliteralcanalsohaveasuffixthatisacombinationofUandL,forunsignedandlong,
respectively.Thesuffixcanbeuppercaseorlowercaseandcanbeinanyorder.
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

http://www.tutorialspoint.com/cgibin/printpage.cgi

13/77

11/4/2015

CQuickGuide

Afloatingpointliteralhasanintegerpart,adecimalpoint,afractionalpart,andanexponentpart.You
canrepresentfloatingpointliteralseitherindecimalformorexponentialform.
Whilerepresentingdecimalform,youmustincludethedecimalpoint,theexponent,orbothandwhile
representingexponentialform,youmustincludetheintegerpart,thefractionalpart,orboth.The
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

http://www.tutorialspoint.com/cgibin/printpage.cgi

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.
Herearesomeexamplesofstringliterals.Allthethreeformsareidenticalstrings.
"hello,dear"
"hello,\
dear"
"hello,""d""ear"

DefiningConstants
TherearetwosimplewaysinCtodefineconstants
Using#definepreprocessor.
Usingconstkeyword.

The#definePreprocessor
Givenbelowistheformtouse#definepreprocessortodefineaconstant
#defineidentifiervalue

Thefollowingexampleexplainsitindetail

http://www.tutorialspoint.com/cgibin/printpage.cgi

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

16/77

11/4/2015

CQuickGuide

Astorageclassdefinesthescopevisibility andlifetimeofvariablesand/orfunctionswithinaC
Program.Theyprecedethetypethattheymodify.WehavefourdifferentstorageclassesinaC
program
auto
register
static
extern

TheautoStorageClass
Theautostorageclassisthedefaultstorageclassforalllocalvariables.
{
intmount;
autointmonth;
}

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

TheregisterStorageClass
Theregisterstorageclassisusedtodefinelocalvariablesthatshouldbestoredinaregisterinsteadof
RAM.Thismeansthatthevariablehasamaximumsizeequaltotheregistersizeusuallyoneword and
can'thavetheunary'&'operatorappliedtoitasitdoesnothaveamemorylocation .
{
registerintmiles;
}

Theregistershouldonlybeusedforvariablesthatrequirequickaccesssuchascounters.Itshouldalso
benotedthatdefining'register'doesnotmeanthatthevariablewillbestoredinaregister.Itmeans
thatitMIGHTbestoredinaregisterdependingonhardwareandimplementationrestrictions.

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

/*functiondeclaration*/
voidfunc(void);

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
programfiles.Whenyouuse'extern',thevariablecannotbeinitializedhowever,itpointsthevariable
nameatastoragelocationthathasbeenpreviouslydefined.
Whenyouhavemultiplefilesandyoudefineaglobalvariableorfunction,whichwillalsobeusedin
otherfiles,thenexternwillbeusedinanotherfiletoprovidethereferenceofdefinedvariableor
function.Justforunderstanding,externisusedtodeclareaglobalvariableorfunctioninanotherfile.
Theexternmodifierismostcommonlyusedwhentherearetwoormorefilessharingthesameglobal
variablesorfunctionsasexplainedbelow.
FirstFile:main.c
#include<stdio.h>

intcount;
externvoidwrite_extern();

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

SecondFile:support.c

http://www.tutorialspoint.com/cgibin/printpage.cgi

18/77

11/4/2015

CQuickGuide

#include<stdio.h>

externintcount;

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

Here,externisbeingusedtodeclarecountinthesecondfile,whereasithasitsdefinitioninthefirst
file,main.c.Now,compilethesetwofilesasfollows
$gccmain.csupport.c

Itwillproducetheexecutableprograma.out.Whenthisprogramisexecuted,itproducesthefollowing
result
5

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

ArithmeticOperators
ThefollowingtableshowsallthearithmeticoperatorssupportedbytheClanguage.AssumevariableA
holds10andvariableBholds20then
ShowExamples

Operator

Description

Example

Addstwooperands.

A+B=30

Subtractssecondoperandfromthefirst.

AB=10

Multipliesbothoperands.

A*B=200

Dividesnumeratorbydenumerator.

B/A=2

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
valueofrightoperand.Ifyes,thenthecondition
becomestrue.

<

Checksifthevalueofleftoperandislessthanthe
valueofrightoperand.Ifyes,thenthecondition
becomestrue.

>=

Checksifthevalueofleftoperandisgreaterthanor
equaltothevalueofrightoperand.Ifyes,thenthe
conditionbecomestrue.

<=

Checksifthevalueofleftoperandislessthanor
equaltothevalueofrightoperand.Ifyes,thenthe
conditionbecomestrue.

Example
A == B

A! = B

isnottrue.

istrue.

A > B

isnottrue.

A < B

istrue.

A >= B

isnottrue.

A <= B

istrue.

LogicalOperators

http://www.tutorialspoint.com/cgibin/printpage.cgi

20/77

11/4/2015

CQuickGuide

FollowingtableshowsallthelogicaloperatorssupportedbyClanguage.AssumevariableAholds1and
variableBholds0,then
ShowExamples

Operator

Description

Example

&&

CalledLogicalANDoperator.Ifboththeoperands
arenonzero,thentheconditionbecomestrue.

||

CalledLogicalOROperator.Ifanyofthetwo
operandsisnonzero,thentheconditionbecomes
true.

CalledLogicalNOTOperator.Itisusedtoreversethe
logicalstateofitsoperand.Ifaconditionistrue,then
LogicalNOToperatorwillmakeitfalse.

A&&B isfalse.

A||B

istrue.

! A&&B istrue.

BitwiseOperators
Bitwiseoperatorworksonbitsandperformbitbybitoperation.Thetruthtablesfor&,|,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

http://www.tutorialspoint.com/cgibin/printpage.cgi

21/77

11/4/2015

CQuickGuide

~A=11000011
ThefollowingtableliststhebitwiseoperatorssupportedbyC.Assumevariable'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.

<<

BinaryLeftShiftOperator.Theleftoperandsvalueis
movedleftbythenumberofbitsspecifiedbythe
rightoperand.

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

>>

BinaryRightShiftOperator.Theleftoperandsvalue
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

Simpleassignmentoperator.Assignsvaluesfrom
rightsideoperandstoleftsideoperand

C=A+Bwillassignthevalue
ofA+BtoC

+=

AddANDassignmentoperator.Itaddstheright
operandtotheleftoperandandassigntheresultto
theleftoperand.

C+=AisequivalenttoC=C
+A

SubtractANDassignmentoperator.Itsubtractsthe

C=AisequivalenttoC=C

http://www.tutorialspoint.com/cgibin/printpage.cgi

22/77

11/4/2015

CQuickGuide

rightoperandfromtheleftoperandandassignsthe
resulttotheleftoperand.

*=

MultiplyANDassignmentoperator.Itmultipliesthe
rightoperandwiththeleftoperandandassignsthe
resulttotheleftoperand.

C*=AisequivalenttoC=C*
A

/=

DivideANDassignmentoperator.Itdividestheleft
operandwiththerightoperandandassignstheresult
totheleftoperand.

C/=AisequivalenttoC=C/
A

%=

ModulusANDassignmentoperator.Ittakesmodulus
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

http://www.tutorialspoint.com/cgibin/printpage.cgi

23/77

11/4/2015

CQuickGuide

OperatorsPrecedenceinC
Operatorprecedencedeterminesthegroupingoftermsinanexpressionanddecideshowanexpression
isevaluated.Certainoperatorshavehigherprecedencethanothersforexample,themultiplication
operatorhasahigherprecedencethantheadditionoperator.
Forexample,x=7+3*2here,xisassigned13,not20becauseoperator*hasahigherprecedence
than+,soitfirstgetsmultipliedwith3*2andthenaddsinto7.
Here,operatorswiththehighestprecedenceappearatthetopofthetable,thosewiththelowestappear
atthebottom.Withinanexpression,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

http://www.tutorialspoint.com/cgibin/printpage.cgi

24/77

11/4/2015

CQuickGuide

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

Cprogramminglanguageassumesanynonzeroandnonnullvaluesastrue,andifitiseitherzero
ornull,thenitisassumedasfalsevalue.
Cprogramminglanguageprovidesthefollowingtypesofdecisionmakingstatements.

S.No.

Statement&Description

ifstatement
Anifstatementconsistsofabooleanexpressionfollowedbyoneormorestatements.

if...elsestatement
Anifstatementcanbefollowedbyanoptionalelsestatement,whichexecuteswhen
theBooleanexpressionisfalse.

nestedifstatements
Youcanuseoneiforelseifstatementinsideanotheriforelseifstatements.

http://www.tutorialspoint.com/cgibin/printpage.cgi

25/77

11/4/2015

CQuickGuide

switchstatement
Aswitchstatementallowsavariabletobetestedforequalityagainstalistofvalues.

nestedswitchstatements
Youcanuseoneswitchstatementinsideanotherswitchstatements.

The?:Operator
Wehavecoveredconditionaloperator?:inthepreviouschapterwhichcanbeusedtoreplace
if...elsestatements.Ithasthefollowinggeneralform
Exp1?Exp2:Exp3;

WhereExp1,Exp2,andExp3areexpressions.Noticetheuseandplacementofthecolon.
Thevalueofa?expressionisdeterminedlikethis
Exp1isevaluated.Ifitistrue,thenExp2isevaluatedandbecomesthevalueoftheentire?
expression.
IfExp1isfalse,thenExp3isevaluatedanditsvaluebecomesthevalueoftheexpression.

CLOOPS
Youmayencountersituations,whenablockofcodeneedstobeexecutedseveralnumberoftimes.In
general,statementsareexecutedsequentially:Thefirststatementinafunctionisexecutedfirst,
followedbythesecond,andsoon.
Programminglanguagesprovidevariouscontrolstructuresthatallowformorecomplicatedexecution
paths.
Aloopstatementallowsustoexecuteastatementorgroupofstatementsmultipletimes.Givenbelowis
thegeneralformofaloopstatementinmostoftheprogramminglanguages

http://www.tutorialspoint.com/cgibin/printpage.cgi

26/77

11/4/2015

CQuickGuide

Cprogramminglanguageprovidesthefollowingtypesofloopstohandleloopingrequirements.

S.No.

LoopType&Description

whileloop
Repeatsastatementorgroupofstatementswhileagivenconditionistrue.Itteststhe
conditionbeforeexecutingtheloopbody.

forloop
Executesasequenceofstatementsmultipletimesandabbreviatesthecodethatmanages
theloopvariable.

do...whileloop
Itismorelikeawhilestatement,exceptthatitteststheconditionattheendoftheloop
body.

nestedloops
Youcanuseoneormoreloopsinsideanyotherwhile,for,ordo..whileloop.

http://www.tutorialspoint.com/cgibin/printpage.cgi

27/77

11/4/2015

CQuickGuide

LoopControlStatements
Loopcontrolstatementschangeexecutionfromitsnormalsequence.Whenexecutionleavesascope,
allautomaticobjectsthatwerecreatedinthatscopearedestroyed.
Csupportsthefollowingcontrolstatements.

S.No.

ControlStatement&Description

breakstatement
Terminatesthelooporswitchstatementandtransfersexecutiontothestatement
immediatelyfollowingthelooporswitch.

continuestatement
Causesthelooptoskiptheremainderofitsbodyandimmediatelyretestitsconditionprior
toreiterating.

gotostatement
Transferscontroltothelabeledstatement.

TheInfiniteLoop
Aloopbecomesaninfiniteloopifaconditionneverbecomesfalse.Theforloopistraditionallyused
forthispurpose.Sincenoneofthethreeexpressionsthatformthe'for'looparerequired,youcan
makeanendlessloopbyleavingtheconditionalexpressionempty.
#include<stdio.h>

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

Whentheconditionalexpressionisabsent,itisassumedtobetrue.Youmayhaveaninitializationand
incrementexpression,butCprogrammersmorecommonlyusethefor; ; constructtosignifyaninfinite
loop.
NOTEYoucanterminateaninfiniteloopbypressingCtrl+Ckeys.

CFUNCTIONS

http://www.tutorialspoint.com/cgibin/printpage.cgi

28/77

11/4/2015

CQuickGuide

Afunctionisagroupofstatementsthattogetherperformatask.EveryCprogramhasatleastone
function,whichismain,andallthemosttrivialprogramscandefineadditionalfunctions.
Youcandivideupyourcodeintoseparatefunctions.Howyoudivideupyourcodeamongdifferent
functionsisuptoyou,butlogicallythedivisionissuchthateachfunctionperformsaspecifictask.
Afunctiondeclarationtellsthecompileraboutafunction'sname,returntype,andparameters.A
functiondefinitionprovidestheactualbodyofthefunction.
TheCstandardlibraryprovidesnumerousbuiltinfunctionsthatyourprogramcancall.Forexample,
strcattoconcatenatetwostrings,memcpytocopyonememorylocationtoanotherlocation,and
manymorefunctions.
Afunctioncanalsobereferredasamethodorasubroutineoraprocedure,etc.

DefiningaFunction
ThegeneralformofafunctiondefinitioninCprogramminglanguageisasfollows
return_typefunction_name(parameterlist){
bodyofthefunction
}

AfunctiondefinitioninCprogrammingconsistsofafunctionheaderandafunctionbody.Hereareall
thepartsofafunction
ReturnTypeAfunctionmayreturnavalue.Thereturn_typeisthedatatypeofthevalue
thefunctionreturns.Somefunctionsperformthedesiredoperationswithoutreturningavalue.
Inthiscase,thereturn_typeisthekeywordvoid.
FunctionNameThisistheactualnameofthefunction.Thefunctionnameandthe
parameterlisttogetherconstitutethefunctionsignature.
ParametersAparameterislikeaplaceholder.Whenafunctionisinvoked,youpassavalueto
theparameter.Thisvalueisreferredtoasactualparameterorargument.Theparameterlist
referstothetype,order,andnumberoftheparametersofafunction.Parametersareoptional
thatis,afunctionmaycontainnoparameters.
FunctionBodyThefunctionbodycontainsacollectionofstatementsthatdefinewhatthe
functiondoes.

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

if(num1>num2)
result=num1;

http://www.tutorialspoint.com/cgibin/printpage.cgi

29/77

11/4/2015

CQuickGuide

else
result=num2;

returnresult;
}

FunctionDeclarations
Afunctiondeclarationtellsthecompileraboutafunctionnameandhowtocallthefunction.The
actualbodyofthefunctioncanbedefinedseparately.
Afunctiondeclarationhasthefollowingparts
return_typefunction_name(parameterlist);

Fortheabovedefinedfunctionmax,thefunctiondeclarationisasfollows
intmax(intnum1,intnum2);

Parameternamesarenotimportantinfunctiondeclarationonlytheirtypeisrequired,sothefollowing
isalsoavaliddeclaration
intmax(int,int);

Functiondeclarationisrequiredwhenyoudefineafunctioninonesourcefileandyoucallthatfunction
inanotherfile.Insuchcase,youshoulddeclarethefunctionatthetopofthefilecallingthefunction.

CallingaFunction
WhilecreatingaCfunction,yougiveadefinitionofwhatthefunctionhastodo.Touseafunction,you
willhavetocallthatfunctiontoperformthedefinedtask.
Whenaprogramcallsafunction,theprogramcontrolistransferredtothecalledfunction.Acalled
functionperformsadefinedtaskandwhenitsreturnstatementisexecutedorwhenitsfunctionending
closingbraceisreached,itreturnstheprogramcontrolbacktothemainprogram.
Tocallafunction,yousimplyneedtopasstherequiredparametersalongwiththefunctionname,andif
thefunctionreturnsavalue,thenyoucanstorethereturnedvalue.Forexample
#include<stdio.h>

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

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

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

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

Wehavekeptmaxalongwithmainandcompiledthesourcecode.Whilerunningthefinalexecutable,it
wouldproducethefollowingresult
Maxvalueis:200

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

S.No.

CallType&Description

Callbyvalue
Thismethodcopiestheactualvalueofanargumentintotheformalparameterofthe
function.Inthiscase,changesmadetotheparameterinsidethefunctionhavenoeffecton
theargument.

Callbyreference
Thismethodcopiestheaddressofanargumentintotheformalparameter.Insidethe
function,theaddressisusedtoaccesstheactualargumentusedinthecall.Thismeansthat
changesmadetotheparameteraffecttheargument.

http://www.tutorialspoint.com/cgibin/printpage.cgi

31/77

11/4/2015

CQuickGuide

Bydefault,Cusescallbyvaluetopassarguments.Ingeneral,itmeansthecodewithinafunction
cannotaltertheargumentsusedtocallthefunction.

CSCOPERULES
Ascopeinanyprogrammingisaregionoftheprogramwhereadefinedvariablecanhaveitsexistence
andbeyondthatvariableitcannotbeaccessed.Therearethreeplaceswherevariablescanbedeclared
inCprogramminglanguage
Insideafunctionorablockwhichiscalledlocalvariables.
Outsideofallfunctionswhichiscalledglobalvariables.
Inthedefinitionoffunctionparameterswhicharecalledformalparameters.
Letusunderstandwhatarelocalandglobalvariables,andformalparameters.

LocalVariables
Variablesthataredeclaredinsideafunctionorblockarecalledlocalvariables.Theycanbeusedonlyby
statementsthatareinsidethatfunctionorblockofcode.Localvariablesarenotknowntofunctions
outsidetheirown.Thefollowingexampleshowshowlocalvariablesareused.Hereallthevariablesa,
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,usuallyontopoftheprogram.Globalvariableshold
theirvaluesthroughoutthelifetimeofyourprogramandtheycanbeaccessedinsideanyofthe
functionsdefinedfortheprogram.
Aglobalvariablecanbeaccessedbyanyfunction.Thatis,aglobalvariableisavailableforuse
throughoutyourentireprogramafteritsdeclaration.Thefollowingprogramshowhowglobalvariables
areusedinaprogram.
#include<stdio.h>

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
functionwilltakepreference.Hereisanexample
#include<stdio.h>

/*globalvariabledeclaration*/
intg=20;

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

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

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
valueofg=10

FormalParameters
Formalparameters,aretreatedaslocalvariableswithinafunctionandtheytakeprecedenceover
globalvariables.Followingisanexample
#include<stdio.h>

/*globalvariabledeclaration*/
inta=20;

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

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,youmustinitializeityourself.Global
variablesareinitializedautomaticallybythesystemwhenyoudefinethemasfollows

DataType

InitialDefaultValue

int

char

'\0'

float

double

pointer

NULL

Itisagoodprogrammingpracticetoinitializevariablesproperly,otherwiseyourprogrammayproduce
unexpectedresults,becauseuninitializedvariableswilltakesomegarbagevaluealreadyavailableat
theirmemorylocation.

CARRAYS
Arraysakindofdatastructurethatcanstoreafixedsizesequentialcollectionofelementsofthesame
type.Anarrayisusedtostoreacollectionofdata,butitisoftenmoreusefultothinkofanarrayasa

http://www.tutorialspoint.com/cgibin/printpage.cgi

34/77

11/4/2015

CQuickGuide

collectionofvariablesofthesametype.
Insteadofdeclaringindividualvariables,suchasnumber0,number1,...,andnumber99,youdeclare
onearrayvariablesuchasnumbersandusenumbers[0],numbers[1],and...,numbers[99]torepresent
individualvariables.Aspecificelementinanarrayisaccessedbyanindex.
Allarraysconsistofcontiguousmemorylocations.Thelowestaddresscorrespondstothefirstelement
andthehighestaddresstothelastelement.

DeclaringArrays
TodeclareanarrayinC,aprogrammerspecifiesthetypeoftheelementsandthenumberofelements
requiredbyanarrayasfollows
typearrayName[arraySize];

Thisiscalledasingledimensionalarray.ThearraySizemustbeanintegerconstantgreaterthanzero
andtypecanbeanyvalidCdatatype.Forexample,todeclarea10elementarraycalledbalanceof
typedouble,usethisstatement
doublebalance[10];

Herebalanceisavariablearraywhichissufficienttoholdupto10doublenumbers.

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

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

Youwillcreateexactlythesamearrayasyoudidinthepreviousexample.Followingisanexampleto
assignasingleelementofthearray
balance[4]=50.0;

Theabovestatementassignsthe5thelementinthearraywithavalueof50.0.Allarrayshave0asthe
indexoftheirfirstelementwhichisalsocalledthebaseindexandthelastindexofanarraywillbetotal

http://www.tutorialspoint.com/cgibin/printpage.cgi

35/77

11/4/2015

CQuickGuide

sizeofthearrayminus1.Shownbelowisthepictorialrepresentationofthearraywediscussedabove

AccessingArrayElements
Anelementisaccessedbyindexingthearrayname.Thisisdonebyplacingtheindexoftheelement
withinsquarebracketsafterthenameofthearray.Forexample
doublesalary=balance[9];

Theabovestatementwilltakethe10thelementfromthearrayandassignthevaluetosalaryvariable.
ThefollowingexampleShowshowtouseallthethreeabovementionedconceptsviz.declaration,
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
ArraysareimportanttoCandshouldneedalotmoreattention.Thefollowingimportantconcepts

http://www.tutorialspoint.com/cgibin/printpage.cgi

36/77

11/4/2015

CQuickGuide

relatedtoarrayshouldbecleartoaCprogrammer

S.No.

Concept&Description

Multidimensionalarrays
Csupportsmultidimensionalarrays.Thesimplestformofthemultidimensionalarrayis
thetwodimensionalarray.

Passingarraystofunctions
Youcanpasstothefunctionapointertoanarraybyspecifyingthearray'snamewithoutan
index.

Returnarrayfromafunction
Callowsafunctiontoreturnanarray.

Pointertoanarray
Youcangenerateapointertothefirstelementofanarraybysimplyspecifyingthearray
name,withoutanyindex.

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

37/77

11/4/2015

CQuickGuide

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Addressofvar1variable:bff5a400
Addressofvar2variable:bff5a3f6

WhatarePointers?
Apointerisavariablewhosevalueistheaddressofanothervariable,i.e.,directaddressofthe
memorylocation.Likeanyvariableorconstant,youmustdeclareapointerbeforeusingittostoreany
variableaddress.Thegeneralformofapointervariabledeclarationis
type*varname;

Here,typeisthepointer'sbasetypeitmustbeavalidCdatatypeandvarnameisthenameofthe
pointervariable.Theasterisk*usedtodeclareapointeristhesameasteriskusedformultiplication.
However,inthisstatementtheasteriskisbeingusedtodesignateavariableasapointer.Takealookat
someofthevalidpointerdeclarations
int*ip;/*pointertoaninteger*/
double*dp;/*pointertoadouble*/
float*fp;/*pointertoafloat*/
char*ch/*pointertoacharacter*/

Theactualdatatypeofthevalueofallpointers,whetherinteger,float,character,orotherwise,isthe
same,alonghexadecimalnumberthatrepresentsamemoryaddress.Theonlydifferencebetween
pointersofdifferentdatatypesisthedatatypeofthevariableorconstantthatthepointerpointsto.

HowtoUsePointers?
Thereareafewimportantoperations,whichwewilldowiththehelpofpointersveryfrequently.a We
defineapointervariable,b assigntheaddressofavariabletoapointerandc finallyaccessthevalueat
theaddressavailableinthepointervariable.Thisisdonebyusingunaryoperator*thatreturnsthe
valueofthevariablelocatedattheaddressspecifiedbyitsoperand.Thefollowingexamplemakesuse
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);

http://www.tutorialspoint.com/cgibin/printpage.cgi

38/77

11/4/2015

CQuickGuide

return0;
}

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

NULLPointers
ItisalwaysagoodpracticetoassignaNULLvaluetoapointervariableincaseyoudonothaveanexact
addresstobeassigned.Thisisdoneatthetimeofvariabledeclaration.ApointerthatisassignedNULL
iscalledanullpointer.
TheNULLpointerisaconstantwithavalueofzerodefinedinseveralstandardlibraries.Considerthe
followingprogram
#include<stdio.h>
intmain(){
int*ptr=NULL;
printf("Thevalueofptris:%x\n",ptr);

return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Thevalueofptris0

Inmostoftheoperatingsystems,programsarenotpermittedtoaccessmemoryataddress0because
thatmemoryisreservedbytheoperatingsystem.However,thememoryaddress0hasspecial
significanceitsignalsthatthepointerisnotintendedtopointtoanaccessiblememorylocation.Butby
convention,ifapointercontainsthenullzerovalue,itisassumedtopointtonothing.
Tocheckforanullpointer,youcanusean'if'statementasfollows
if(ptr)/*succeedsifpisnotnull*/
if(!ptr)/*succeedsifpisnull*/

PointersinDetail
PointershavemanybuteasyconceptsandtheyareveryimportanttoCprogramming.Thefollowing
importantpointerconceptsshouldbecleartoanyCprogrammer

S.No.

Concept&Description

http://www.tutorialspoint.com/cgibin/printpage.cgi

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++

http://www.tutorialspoint.com/cgibin/printpage.cgi

40/77

11/4/2015

CQuickGuide

Actually,youdonotplacethenullcharacterattheendofastringconstant.TheCcompiler
automaticallyplacesthe'\0'attheendofthestringwhenitinitializesthearray.Letustrytoprintthe
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.

http://www.tutorialspoint.com/cgibin/printpage.cgi

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

42/77

11/4/2015

CQuickGuide

Arraysallowtodefinetypeofvariablesthatcanholdseveraldataitemsofthesamekind.Similarly
structureisanotheruserdefineddatatypeavailableinCthatallowstocombinedataitemsof
differentkinds.
Structuresareusedtorepresentarecord.Supposeyouwanttokeeptrackofyourbooksinalibrary.
Youmightwanttotrackthefollowingattributesabouteachbook
Title
Author
Subject
BookID

DefiningaStructure
Todefineastructure,youmustusethestructstatement.Thestructstatementdefinesanewdatatype,
withmorethanonemember.Theformatofthestructstatementisasfollows
struct[structuretag]{
memberdefinition;
memberdefinition;
...
memberdefinition;
}[oneormorestructurevariables];

Thestructuretagisoptionalandeachmemberdefinitionisanormalvariabledefinition,suchasinti
orfloatforanyothervalidvariabledefinition.Attheendofthestructure'sdefinition,beforethefinal
semicolon,youcanspecifyoneormorestructurevariablesbutitisoptional.Hereisthewayyouwould
declaretheBookstructure
structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
}book;

AccessingStructureMembers
Toaccessanymemberofastructure,weusethememberaccessoperator . .Thememberaccess
operatoriscodedasaperiodbetweenthestructurevariablenameandthestructurememberthatwe
wishtoaccess.Youwouldusethekeywordstructtodefinevariablesofstructuretype.Thefollowing
exampleshowshowtouseastructureinaprogram
#include<stdio.h>
#include<string.h>

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

43/77

11/4/2015

CQuickGuide

};

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

/*book1specification*/
strcpy(Book1.title,"CProgramming");
strcpy(Book1.author,"NuhaAli");
strcpy(Book1.subject,"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy(Book2.title,"TelecomBilling");
strcpy(Book2.author,"ZaraAli");
strcpy(Book2.subject,"TelecomBillingTutorial");
Book2.book_id=6495700;

/*printBook1info*/
printf("Book1title:%s\n",Book1.title);
printf("Book1author:%s\n",Book1.author);
printf("Book1subject:%s\n",Book1.subject);
printf("Book1book_id:%d\n",Book1.book_id);
/*printBook2info*/
printf("Book2title:%s\n",Book2.title);
printf("Book2author:%s\n",Book2.author);
printf("Book2subject:%s\n",Book2.subject);
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];

http://www.tutorialspoint.com/cgibin/printpage.cgi

44/77

11/4/2015

CQuickGuide

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

/*book1specification*/
strcpy(Book1.title,"CProgramming");
strcpy(Book1.author,"NuhaAli");
strcpy(Book1.subject,"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy(Book2.title,"TelecomBilling");
strcpy(Book2.author,"ZaraAli");
strcpy(Book2.subject,"TelecomBillingTutorial");
Book2.book_id=6495700;

/*printBook1info*/
printBook(Book1);
/*PrintBook2info*/
printBook(Book2);
return0;
}
voidprintBook(structBooksbook){
printf("Booktitle:%s\n",book.title);
printf("Bookauthor:%s\n",book.author);
printf("Booksubject:%s\n",book.subject);
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;

http://www.tutorialspoint.com/cgibin/printpage.cgi

45/77

11/4/2015

CQuickGuide

Now,youcanstoretheaddressofastructurevariableintheabovedefinedpointervariable.Tofindthe
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(Book1.title,"CProgramming");
strcpy(Book1.author,"NuhaAli");
strcpy(Book1.subject,"CProgrammingTutorial");
Book1.book_id=6495407;
/*book2specification*/
strcpy(Book2.title,"TelecomBilling");
strcpy(Book2.author,"ZaraAli");
strcpy(Book2.subject,"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);

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
BitFieldsallowthepackingofdatainastructure.Thisisespeciallyusefulwhenmemoryordatastorage
isatapremium.Typicalexamplesinclude
Packingseveralobjectsintoamachineword.e.g.1bitflagscanbecompacted.
Readingexternalfileformatsnonstandardfileformatscouldbereadin,e.g.,9bitintegers.
Callowsustodothisinastructuredefinitionbyputting:bitlengthafterthevariable.Forexample
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
ofthefieldislessthanorequaltotheintegerwordlengthofthecomputer.Ifthisisnotthecase,then
somecompilersmayallowmemoryoverlapforthefieldswhileotherswouldstorethenextfieldinthe
nextword.

CUNIONS
AunionisaspecialdatatypeavailableinCthatallowstostoredifferentdatatypesinthesame
memorylocation.Youcandefineaunionwithmanymembers,butonlyonemembercancontaina
valueatanygiventime.Unionsprovideanefficientwayofusingthesamememorylocationfor
multiplepurpose.

DefiningaUnion
Todefineaunion,youmustusetheunionstatementinthesamewayasyoudidwhiledefininga
structure.Theunionstatementdefinesanewdatatypewithmorethanonememberforyourprogram.
Theformatoftheunionstatementisasfollows

http://www.tutorialspoint.com/cgibin/printpage.cgi

47/77

11/4/2015

CQuickGuide

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

Theuniontagisoptionalandeachmemberdefinitionisanormalvariabledefinition,suchasintior
floatforanyothervalidvariabledefinition.Attheendoftheunion'sdefinition,beforethefinal
semicolon,youcanspecifyoneormoreunionvariablesbutitisoptional.Hereisthewayyouwould
defineauniontypenamedDatahavingthreemembersi,f,andstr
unionData{
inti;
floatf;
charstr[20];
}data;

Now,avariableofDatatypecanstoreaninteger,afloatingpointnumber,orastringofcharacters.It
meansasinglevariable,i.e.,samememorylocation,canbeusedtostoremultipletypesofdata.Youcan
useanybuiltinoruserdefineddatatypesinsideaunionbasedonyourrequirement.
Thememoryoccupiedbyaunionwillbelargeenoughtoholdthelargestmemberoftheunion.For
example,intheaboveexample,Datatypewilloccupy20bytesofmemoryspacebecausethisisthe
maximumspacewhichcanbeoccupiedbyacharacterstring.Thefollowingexampledisplaysthetotal
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
access.Youwouldusethekeyworduniontodefinevariablesofuniontype.Thefollowingexample

http://www.tutorialspoint.com/cgibin/printpage.cgi

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(data.str,"CProgramming");
printf("data.i:%d\n",data.i);
printf("data.f:%f\n",data.f);
printf("data.str:%s\n",data.str);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
data.i:1917853763
data.f:4122360580327794860452759994368.000000
data.str: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);

http://www.tutorialspoint.com/cgibin/printpage.cgi

49/77

11/4/2015

CQuickGuide

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

strcpy(data.str,"CProgramming");
printf("data.str:%s\n",data.str);
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
data.i:10
data.f:220.500000
data.str:CProgramming

Here,allthemembersaregettingprintedverywellbecauseonememberisbeingusedatatime.

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

Thisstructurerequires8bytesofmemoryspacebutinactual,wearegoingtostoreeither0or1ineach
ofthevariables.TheCprogramminglanguageoffersabetterwaytoutilizethememoryspaceinsuch
situations.
Ifyouareusingsuchvariablesinsideastructurethenyoucandefinethewidthofavariablewhichtells
theCcompilerthatyouaregoingtouseonlythosenumberofbytes.Forexample,theabovestructure
canberewrittenasfollows
struct{
unsignedintwidthValidated:1;
unsignedintheightValidated:1;
}status;

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

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'svalueisinterpreted.Thetype
maybeint,signedint,orunsignedint.

member_name

Thenameofthebitfield.

width

Thenumberofbitsinthebitfield.Thewidthmustbelessthanorequaltothe
bitwidthofthespecifiedtype.

Thevariablesdefinedwithapredefinedwidtharecalledbitfields.Abitfieldcanholdmorethana
singlebitforexample,ifyouneedavariabletostoreavaluefrom0to7,thenyoucandefineabitfield
withawidthof3bitsasfollows
struct{
unsignedintage:3;
}Age;

http://www.tutorialspoint.com/cgibin/printpage.cgi

51/77

11/4/2015

CQuickGuide

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

Whentheabovecodeiscompileditwillcompilewithawarningandwhenexecuted,itproducesthe
followingresult
Sizeof(Age):4
Age.age:4
Age.age:7
Age.age:0

CTYPEDEF
TheCprogramminglanguageprovidesakeywordcalledtypedef,whichyoucanusetogiveatype,a
newname.FollowingisanexampletodefineatermBYTEforonebytenumbers
typedefunsignedcharBYTE;

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

Byconvention,uppercaselettersareusedforthesedefinitionstoremindtheuserthatthetypenameis
reallyasymbolicabbreviation,butyoucanuselowercase,asfollows
typedefunsignedcharbyte;

Youcanusetypedeftogiveanametoyouruserdefineddatatypesaswell.Forexample,youcanuse
typedefwithstructuretodefineanewdatatypeandthenusethatdatatypetodefinestructure

http://www.tutorialspoint.com/cgibin/printpage.cgi

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(book.title,"CProgramming");
strcpy(book.author,"NuhaAli");
strcpy(book.subject,"CProgrammingTutorial");
book.book_id=6495407;

printf("Booktitle:%s\n",book.title);
printf("Bookauthor:%s\n",book.author);
printf("Booksubject:%s\n",book.subject);
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(){

http://www.tutorialspoint.com/cgibin/printpage.cgi

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,itmeanstofeedsomedataintoaprogram.Aninputcanbegivenintheformofa
fileorfromthecommandline.Cprogrammingprovidesasetofbuiltinfunctionstoreadthegiven
inputandfeedittotheprogramasperrequirement.
WhenwesayOutput,itmeanstodisplaysomedataonscreen,printer,orinanyfile.Cprogramming
providesasetofbuiltinfunctionstooutputthedataonthecomputerscreenaswellastosaveitintext
orbinaryfiles.

TheStandardFiles
Cprogrammingtreatsallthedevicesasfiles.Sodevicessuchasthedisplayareaddressedinthesame
wayasfilesandthefollowingthreefilesareautomaticallyopenedwhenaprogramexecutestoprovide
accesstothekeyboardandscreen.

StandardFile

FilePointer

Device

Standardinput

stdin

Keyboard

Standardoutput

stdout

Screen

Standarderror

stderr

Yourscreen

Thefilepointersarethemeanstoaccessthefileforreadingandwritingpurpose.Thissectionexplains
howtoreadvaluesfromthescreenandhowtoprinttheresultonthescreen.

ThegetcharandputcharFunctions
Theintgetcharvoid functionreadsthenextavailablecharacterfromthescreenandreturnsitasan
integer.Thisfunctionreadsonlysinglecharacteratatime.Youcanusethismethodintheloopincase
youwanttoreadmorethanonecharacterfromthescreen.
Theintputcharintc functionputsthepassedcharacteronthescreenandreturnsthesamecharacter.
Thisfunctionputsonlysinglecharacteratatime.Youcanusethismethodintheloopincaseyouwant
todisplaymorethanonecharacteronthescreen.Checkthefollowingexample
#include<stdio.h>
intmain(){

http://www.tutorialspoint.com/cgibin/printpage.cgi

54/77

11/4/2015

CQuickGuide

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

Whentheabovecodeiscompiledandexecuted,itwaitsforyoutoinputsometext.Whenyouentera
textandpressenter,thentheprogramproceedsandreadsonlyasinglecharacteranddisplaysitas
follows
$./a.out
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,itwaitsforyoutoinputsometext.Whenyouentera
textandpressenter,thentheprogramproceedsandreadsthecompletelinetillend,anddisplaysitas
follows
$./a.out
Enteravalue:thisistest
Youentered:Thisistest

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

55/77

11/4/2015

CQuickGuide

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

Whentheabovecodeiscompiledandexecuted,itwaitsforyoutoinputsometext.Whenyouentera
textandpressenter,thenprogramproceedsandreadstheinputanddisplaysitasfollows
$./a.out
Enteravalue:seven7
Youentered:seven7

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

CFILEI/O
ThelastchapterexplainedthestandardinputandoutputdeviceshandledbyCprogramminglanguage.
ThischaptercoverhowCprogrammerscancreate,open,closetextorbinaryfilesfortheirdata
storage.
Afilerepresentsasequenceofbytes,regardlessofitbeingatextfileorabinaryfile.Cprogramming
languageprovidesaccessonhighlevelfunctionsaswellaslowlevelOS levelcallstohandlefileonyour
storagedevices.Thischapterwilltakeyouthroughtheimportantcallsforfilemanagement.

OpeningFiles
Youcanusethefopenfunctiontocreateanewfileortoopenanexistingfile.Thiscallwillinitializean
objectofthetypeFILE,whichcontainsalltheinformationnecessarytocontrolthestream.The
prototypeofthisfunctioncallisasfollows
FILE*fopen(constchar*filename,constchar*mode);

Here,filenameisastringliteral,whichyouwillusetonameyourfile,andaccessmodecanhaveone
ofthefollowingvalues

http://www.tutorialspoint.com/cgibin/printpage.cgi

56/77

11/4/2015

CQuickGuide

Mode

Description

Opensanexistingtextfileforreadingpurpose.

Opensatextfileforwriting.Ifitdoesnotexist,thenanewfileiscreated.Hereyour
programwillstartwritingcontentfromthebeginningofthefile.

Opensatextfileforwritinginappendingmode.Ifitdoesnotexist,thenanewfileis
created.Hereyourprogramwillstartappendingcontentintheexistingfilecontent.

r+

Opensatextfileforbothreadingandwriting.

w+

Opensatextfileforbothreadingandwriting.Itfirsttruncatesthefiletozerolengthifit
exists,otherwisecreatesafileifitdoesnotexist.

a+

Opensatextfileforbothreadingandwriting.Itcreatesthefileifitdoesnotexist.The
readingwillstartfromthebeginningbutwritingcanonlybeappended.

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

ClosingaFile
Tocloseafile,usethefclosefunction.Theprototypeofthisfunctionis
intfclose(FILE*fp);

Thefclose functionreturnszeroonsuccess,orEOFifthereisanerrorinclosingthefile.This
functionactuallyflushesanydatastillpendinginthebuffertothefile,closesthefile,andreleasesany
memoryusedforthefile.TheEOFisaconstantdefinedintheheaderfilestdio.h.
TherearevariousfunctionsprovidedbyCstandardlibrarytoreadandwriteafile,characterby
character,orintheformofafixedlengthstring.

WritingaFile
Followingisthesimplestfunctiontowriteindividualcharacterstoastream
intfputc(intc,FILE*fp);

Thefunctionfputcwritesthecharactervalueoftheargumentctotheoutputstreamreferencedbyfp.
ItreturnsthewrittencharacterwrittenonsuccessotherwiseEOFifthereisanerror.Youcanusethe
followingfunctionstowriteanullterminatedstringtoastream
intfputs(constchar*s,FILE*fp);

http://www.tutorialspoint.com/cgibin/printpage.cgi

57/77

11/4/2015

CQuickGuide

Thefunctionfputswritesthestringstotheoutputstreamreferencedbyfp.Itreturnsanonnegative
valueonsuccess,otherwiseEOFisreturnedincaseofanyerror.Youcanuseintfprintf
F I LE f p, constchar f ormat, . . . functionaswelltowriteastringintoafile.Trythefollowing
example.
Makesureyouhave/tmpdirectoryavailable.Ifitisnot,thenbeforeproceeding,youmustcreatethis
directoryonyourmachine.
#include<stdio.h>
main(){
FILE*fp;
fp=fopen("/tmp/test.txt","w+");
fprintf(fp,"Thisistestingforfprintf...\n");
fputs("Thisistestingforfputs...\n",fp);
fclose(fp);
}

Whentheabovecodeiscompiledandexecuted,itcreatesanewfiletest.txtin/tmpdirectoryand
writestwolinesusingtwodifferentfunctions.Letusreadthisfileinthenextsection.

ReadingaFile
Givenbelowisthesimplestfunctiontoreadasinglecharacterfromafile
intfgetc(FILE*fp);

Thefgetcfunctionreadsacharacterfromtheinputfilereferencedbyfp.Thereturnvalueisthe
characterread,orincaseofanyerror,itreturnsEOF.Thefollowingfunctionallowstoreadastring
fromastream
char*fgets(char*buf,intn,FILE*fp);

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

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'sseealittlemoreindetailaboutwhathappenedhere.First,fscanfreadjustThisbecauseafter
that,itencounteredaspace,secondcallisforfgetswhichreadstheremaininglinetillitencountered
endofline.Finally,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,butisaseparatestepinthecompilationprocess.In
simpleterms,aCPreprocessorisjustatextsubstitutiontoolanditinstructsthecompilertodo
requiredpreprocessingbeforetheactualcompilation.We'llrefertotheCPreprocessorasCPP.
Allpreprocessorcommandsbeginwithahashsymbol # .Itmustbethefirstnonblankcharacter,and
forreadability,apreprocessordirectiveshouldbegininthefirstcolumn.Thefollowingsectionlists
downalltheimportantpreprocessordirectives

Directive

Description

#define

Substitutesapreprocessormacro.

#include

Insertsaparticularheaderfromanotherfile.

#undef

Undefinesapreprocessormacro.

http://www.tutorialspoint.com/cgibin/printpage.cgi

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"

ThesedirectivestelltheCPPtogetstdio.hfromSystemLibrariesandaddthetexttothecurrent
sourcefile.ThenextlinetellsCPPtogetmyheader.hfromthelocaldirectoryandaddthecontentto
thecurrentsourcefile.
#undefFILE_SIZE
#defineFILE_SIZE42

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

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

IttellstheCPPtoprocessthestatementsenclosedifDEBUGisdefined.Thisisusefulifyoupassthe
DDEBUGflagtothegcccompileratthetimeofcompilation.ThiswilldefineDEBUG,soyoucanturn

http://www.tutorialspoint.com/cgibin/printpage.cgi

60/77

11/4/2015

CQuickGuide

debuggingonandoffontheflyduringcompilation.

PredefinedMacros
ANSICdefinesanumberofmacros.Althougheachoneisavailableforuseinprogramming,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__);
}

Whentheabovecodeinafiletest.ciscompiledandexecuted,itproducesthefollowingresult
File:test.c
Date:Jun22012
Time:03:36:24
Line:8
ANSI:1

PreprocessorOperators
TheCpreprocessoroffersthefollowingoperatorstohelpcreatemacros

TheMacroContinuation(\)Operator
Amacroisnormallyconfinedtoasingleline.Themacrocontinuationoperator(\)isusedtocontinuea
macrothatistoolongforasingleline.Forexample

http://www.tutorialspoint.com/cgibin/printpage.cgi

61/77

11/4/2015

CQuickGuide

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

TheStringize # Operator
Thestringizeornumbersignoperator '#' ,whenusedwithinamacrodefinition,convertsamacro
parameterintoastringconstant.Thisoperatormaybeusedonlyinamacrohavingaspecified
argumentorparameterlist.Forexample
#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 ## withinamacrodefinitioncombinestwoarguments.Itpermitstwo
separatetokensinthemacrodefinitiontobejoinedintoasingletoken.Forexample
#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

http://www.tutorialspoint.com/cgibin/printpage.cgi

62/77

11/4/2015

CQuickGuide

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

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Hereisthemessage:Youwish!

ParameterizedMacros
OneofthepowerfulfunctionsoftheCPPistheabilitytosimulatefunctionsusingparameterized
macros.Forexample,wemighthavesomecodetosquareanumberasfollows
intsquare(intx){
returnx*x;
}

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

Macroswithargumentsmustbedefinedusingthe#definedirectivebeforetheycanbeused.The
argumentlistisenclosedinparenthesesandmustimmediatelyfollowthemacroname.Spacesarenot
allowedbetweenthemacronameandopenparenthesis.Forexample
#include<stdio.h>
#defineMAX(x,y)((x)>(y)?(x):(y))
intmain(void){
printf("Maxbetween20and10is%d\n",MAX(10,20));
return0;
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult
Maxbetween20and10is20

CHEADERFILES
Aheaderfileisafilewithextension.hwhichcontainsCfunctiondeclarationsandmacrodefinitionsto

http://www.tutorialspoint.com/cgibin/printpage.cgi

63/77

11/4/2015

CQuickGuide

besharedbetweenseveralsourcefiles.Therearetwotypesofheaderfiles:thefilesthatthe
programmerwritesandthefilesthatcomeswithyourcompiler.
YourequesttouseaheaderfileinyourprogrambyincludingitwiththeCpreprocessingdirective
#include,likeyouhaveseeninclusionofstdio.hheaderfile,whichcomesalongwithyourcompiler.
Includingaheaderfileisequaltocopyingthecontentoftheheaderfilebutwedonotdoitbecauseit
willbeerrorproneanditisnotagoodideatocopythecontentofaheaderfileinthesourcefiles,
especiallyifwehavemultiplesourcefilesinaprogram.
AsimplepracticeinCorC++programsisthatwekeepalltheconstants,macros,systemwideglobal
variables,andfunctionprototypesintheheaderfilesandincludethatheaderfilewhereveritis
required.

IncludeSyntax
Boththeuserandthesystemheaderfilesareincludedusingthepreprocessingdirective#include.It
hasthefollowingtwoforms
#include<file>

Thisformisusedforsystemheaderfiles.Itsearchesforafilenamed'file'inastandardlistofsystem
directories.YoucanprependdirectoriestothislistwiththeIoptionwhilecompilingyoursourcecode.
#include"file"

Thisformisusedforheaderfilesofyourownprogram.Itsearchesforafilenamed'file'inthedirectory
containingthecurrentfile.YoucanprependdirectoriestothislistwiththeIoptionwhilecompiling
yoursourcecode.

IncludeOperation
The#includedirectiveworksbydirectingtheCpreprocessortoscanthespecifiedfileasinputbefore
continuingwiththerestofthecurrentsourcefile.Theoutputfromthepreprocessorcontainsthe
outputalreadygenerated,followedbytheoutputresultingfromtheincludedfile,followedbythe
outputthatcomesfromthetextafterthe#includedirective.Forexample,ifyouhaveaheaderfile
header.hasfollows
char*test(void);

andamainprogramcalledprogram.cthatusestheheaderfile,likethis
intx;
#include"header.h"
intmain(void){
puts(test());
}

thecompilerwillseethesametokenstreamasitwouldifprogram.cread.
intx;
char*test(void);

http://www.tutorialspoint.com/cgibin/printpage.cgi

64/77

11/4/2015

CQuickGuide

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

OnceOnlyHeaders
Ifaheaderfilehappenstobeincludedtwice,thecompilerwillprocessitscontentstwiceanditwill
resultinanerror.Thestandardwaytopreventthisistoenclosetheentirerealcontentsofthefileina
conditional,likethis
#ifndefHEADER_FILE
#defineHEADER_FILE
theentireheaderfilefile
#endif

Thisconstructiscommonlyknownasawrapper#ifndef.Whentheheaderisincludedagain,the
conditionalwillbefalse,becauseHEADER_FILEisdefined.Thepreprocessorwillskipovertheentire
contentsofthefile,andthecompilerwillnotseeittwice.

ComputedIncludes
Sometimesitisnecessarytoselectoneoftheseveraldifferentheaderfilestobeincludedintoyour
program.Forinstance,theymightspecifyconfigurationparameterstobeusedondifferentsortsof
operatingsystems.Youcoulddothiswithaseriesofconditionalsasfollows
#ifSYSTEM_1
#include"system_1.h"
#elifSYSTEM_2
#include"system_2.h"
#elifSYSTEM_3
...
#endif

Butasitgrows,itbecomestedious,insteadthepreprocessorofferstheabilitytouseamacroforthe
headername.Thisiscalledacomputedinclude.Insteadofwritingaheadernameasthedirect
argumentof#include,yousimplyputamacronamethere
#defineSYSTEM_H"system_1.h"
...
#includeSYSTEM_H

SYSTEM_Hwillbeexpanded,andthepreprocessorwilllookforsystem_1.hasifthe#includehad
beenwrittenthatwayoriginally.SYSTEM_HcouldbedefinedbyyourMakefilewithaDoption.

CTYPECASTING
Typecastingisawaytoconvertavariablefromonedatatypetoanotherdatatype.Forexample,ifyou
wanttostorea'long'valueintoasimpleintegerthenyoucantypecast'long'to'int'.Youcanconvertthe
valuesfromonetypetoanotherexplicitlyusingthecastoperatorasfollows

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
specifiedexplicitlythroughtheuseofthecastoperator.Itisconsideredgoodprogrammingpractice
tousethecastoperatorwhenevertypeconversionsarenecessary.

IntegerPromotion
Integerpromotionistheprocessbywhichvaluesofintegertype"smaller"thanintorunsignedint
areconvertedeithertointorunsignedint.Consideranexampleofaddingacharacterwithan
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.

http://www.tutorialspoint.com/cgibin/printpage.cgi

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

67/77

11/4/2015

CQuickGuide

Valueofsum:116.000000

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

CERRORHANDLING
Assuch,Cprogrammingdoesnotprovidedirectsupportforerrorhandlingbutbeingasystem
programminglanguage,itprovidesyouaccessatlowerlevelintheformofreturnvalues.MostoftheC
orevenUnixfunctioncallsreturn1orNULLincaseofanyerrorandsetanerrorcodeerrno.Itisset
asaglobalvariableandindicatesanerroroccurredduringanyfunctioncall.Youcanfindvariouserror
codesdefinedin<error.h>headerfile.
SoaCprogrammercancheckthereturnedvaluesandcantakeappropriateactiondependingonthe
returnvalue.Itisagoodpractice,toseterrnoto0atthetimeofinitializingaprogram.Avalueof0
indicatesthatthereisnoerrorintheprogram.

errno,perror.andstrerror
TheCprogramminglanguageprovidesperrorandstrerrorfunctionswhichcanbeusedtodisplaythe
textmessageassociatedwitherrno.
Theperrorfunctiondisplaysthestringyoupasstoit,followedbyacolon,aspace,andthenthe
textualrepresentationofthecurrenterrnovalue.
Thestrerrorfunction,whichreturnsapointertothetextualrepresentationofthecurrent
errnovalue.
Let'strytosimulateanerrorconditionandtrytoopenafilewhichdoesnotexist.HereI'musingboth
thefunctionstoshowtheusage,butyoucanuseoneormorewaysofprintingyourerrors.Second
importantpointtonoteisthatyoushouldusestderrfilestreamtooutputalltheerrors.
#include<stdio.h>
#include<errno.h>
#include<string.h>
externinterrno;
intmain(){
FILE*pf;
interrnum;
pf=fopen("unexist.txt","rb");

if(pf==NULL){

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
successfuloperation.Here,EXIT_SUCCESSisamacroanditisdefinedas0.
Ifyouhaveanerrorconditioninyourprogramandyouarecomingoutthenyoushouldexitwitha
statusEXIT_FAILUREwhichisdefinedas1.Solet'swriteaboveprogramasfollows
#include<stdio.h>
#include<stdlib.h>

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
Recursionistheprocessofrepeatingitemsinaselfsimilarway.Inprogramminglanguages,ifa
programallowsyoutocallafunctioninsidethesamefunction,thenitiscalledarecursivecallofthe
function.
voidrecursion(){
recursion();/*functioncallsitself*/
}
intmain(){
recursion();
}

TheCprogramminglanguagesupportsrecursion,i.e.,afunctiontocallitself.Butwhileusing
recursion,programmersneedtobecarefultodefineanexitconditionfromthefunction,otherwiseit
willgointoaninfiniteloop.
Recursivefunctionsareveryusefultosolvemanymathematicalproblems,suchascalculatingthe
factorialofanumber,generatingFibonacciseries,etc.

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

http://www.tutorialspoint.com/cgibin/printpage.cgi

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,insteadofpredefinednumberofparameters.TheC
programminglanguageprovidesasolutionforthissituationandyouareallowedtodefineafunction
whichcanacceptvariablenumberofparametersbasedonyourrequirement.Thefollowingexample
showsthedefinitionofsuchafunction.
intfunc(int,...){

http://www.tutorialspoint.com/cgibin/printpage.cgi

71/77

11/4/2015

CQuickGuide

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

Itshouldbenotedthatthefunctionfunchasitslastargumentasellipses,i.e.threedotes(...)andthe
onejustbeforetheellipsesisalwaysanintwhichwillrepresentthetotalnumbervariablearguments
passed.Tousesuchfunctionality,youneedtomakeuseofstdarg.hheaderfilewhichprovidesthe
functionsandmacrostoimplementthefunctionalityofvariableargumentsandfollowthegivensteps
Defineafunctionwithitslastparameterasellipsesandtheonejustbeforetheellipsesisalways
anintwhichwillrepresentthenumberofarguments.
Createava_listtypevariableinthefunctiondefinition.Thistypeisdefinedinstdarg.hheader
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));

http://www.tutorialspoint.com/cgibin/printpage.cgi

72/77

11/4/2015

CQuickGuide

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

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult.Itshouldbenotedthat
thefunctionaveragehasbeencalledtwiceandeachtimethefirstargumentrepresentsthetotal
numberofvariableargumentsbeingpassed.Onlyellipseswillbeusedtopassvariablenumberof
arguments.
Averageof2,3,4,5=3.500000
Averageof5,10,15=10.000000

CMEMORYMANAGEMENT
ThischapterexplainsdynamicmemorymanagementinC.TheCprogramminglanguageprovides
severalfunctionsformemoryallocationandmanagement.Thesefunctionscanbefoundinthe
<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
array.Forexample,tostoreanameofanyperson,itcangouptoamaximumof100characters,soyou
candefinesomethingasfollows
charname[100];

http://www.tutorialspoint.com/cgibin/printpage.cgi

73/77

11/4/2015

CQuickGuide

Butnowletusconsiderasituationwhereyouhavenoideaaboutthelengthofthetextyouneedto
store,forexample,youwanttostoreadetaileddescriptionaboutatopic.Hereweneedtodefinea
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
realloc.Letuschecktheaboveprogramonceagainandmakeuseofreallocandfreefunctions
#include<stdio.h>
#include<stdlib.h>

http://www.tutorialspoint.com/cgibin/printpage.cgi

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
theprogram.Followingisasimpleexamplewhichchecksifthereisanyargumentsuppliedfromthe
commandlineandtakeactionaccordingly

http://www.tutorialspoint.com/cgibin/printpage.cgi

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.
$./a.outtesting
Theargumentsuppliedistesting

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

Whentheabovecodeiscompiledandexecutedwithoutpassinganyargument,itproducesthefollowing
result.
$./a.out
Oneargumentexpected

Itshouldbenotedthatargv[0]holdsthenameoftheprogramitselfandargv[1]isapointertothe
firstcommandlineargumentsupplied,and*argv[n]isthelastargument.Ifnoargumentsaresupplied,
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");

http://www.tutorialspoint.com/cgibin/printpage.cgi

76/77

11/4/2015

CQuickGuide

}
}

Whentheabovecodeiscompiledandexecutedwithasingleargumentseparatedbyspacebutinside
doublequotes,itproducesthefollowingresult.
$./a.out"testing1testing2"
Progranmname./a.out
Theargumentsuppliedistesting1testing2

http://www.tutorialspoint.com/cgibin/printpage.cgi

77/77

Potrebbero piacerti anche