Sunteți pe pagina 1din 84

1.1.

1 TrigraphCharacters

Atrigraphsequencefoundinthesourcecodeisconvertedtoitsrespective
translationcharacter.Thisallowspeopletoentercertaincharactersthatarenot
allowedundersome(rare)platforms.
Trigraph Sequence Translation Character
??= #
??( [
??/ \
??) ]
??' ^
??< {
??! |
??> }
??- ~
Example:

printf("No???/n");

translatesinto:

printf("No?\n");

1.1.2 Escapesequences

Thefollowingescapesequencesallowspecialcharacterstobeputintothesource
code.
Escape Name Meaning
Sequence
\a Alert Producesanaudibleorvisiblealert.
\b Backspace Movesthecursorbackoneposition(nondestructive).
\f FormFeed Movesthecursortothefirstpositionofthenextpage.
\n NewLine Movesthecursortothefirstpositionofthenextline.
\r Carriage Movesthecursortothefirstpositionofthecurrentline.
Return
\t Horizontal Movesthecursortothenexthorizontaltabularposition.
Tab
\v VerticalTab Movesthecursortothenextverticaltabularposition.
\' Producesasinglequote.
\" Producesadoublequote.
\? Producesaquestionmark.
\\ Producesasinglebackslash.
\0 Producesanullcharacter.
\ddd Definesonecharacterbytheoctaldigits(base8number).Multiple
charactersmaybedefinedinthesameescapesequence,butthe
valueisimplementationspecific(seeexamples).
\xdd Definesonecharacterbythehexadecimaldigit(base16number).
Examples:

printf("\12");
Producesthedecimalcharacter10(x0AHex).

printf("\xFF");
Producesthedecimalcharacter1or255(dependingonsign).

printf("\x123");
Producesasinglecharacter(valueisundefined).Maycauseerrors.

printf("\0222");
Producestwocharacterswhosevaluesareimplementationspecific.

1.1.3 Comments

Commentsinthesourcecodeareignoredbythecompiler.Theyareencapsulated
startingwith/*andendingwith*/.AccordingtotheANSIstandard,nested
commentsarenotallowed,althoughsomeimplementationsallowit.Singleline
commentsarebecomingmorecommon,althoughnotdefinedintheANSIstandard.
Singlelinecommentsbeginwith//andareautomaticallyterminatedattheendof
thecurrentline.

1.2.1Keywords

Thefollowingkeywordsarereservedandmaynotbeusedasanidentifierforany
otherpurpose.
auto double int long
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

1.2.2Variables

Avariablemaybedefinedusinganyuppercaseorlowercasecharacter,anumerical
digit(0through9),andtheunderscorecharacter(_).Thefirstcharacterofthe
variablemaynotbeanumericaldigitorunderscore.Variablenamesarecase
sensitive.
Thescopeofthevariable(whereitcanbeused),isdeterminedbywhereitis
defined.Ifitisdefinedoutsideanyblockorlistofparameters,thenithasfilescope.
Thismeansitmaybeaccessedanywhereinthecurrentsourcecodefile.Thisis
normallycalledaglobalvariableandisnormallydefinedatthetopofthesource
code.Allothertypesofvariablesarelocalvariables.Ifavariableisdefinedinablock
(encapsulatedwith{and}),thenitsscopebeginswhenthevariableisdefinedand
endswhenithitstheterminating}.Thisiscalledblockscope.Ifthevariableis
definedinafunctionprototype,thenthevariablemayonlybeaccessedinthat
function.Thisiscalledfunctionprototypescope.
Accesstovariablesoutsideoftheirfilescopecanbemadebyusinglinkage.Linkage
isdonebyplacingthekeywordexternpriortoavariabledeclaration.Thisallowsa
variablethatisdefinedinanothersourcecodefiletobeaccessed.
Variablesdefinedwithinafunctionscopehaveautomaticstorageduration.Thelife
ofthevariableisdeterminedbythelifeofthefunction.Spaceisallocatedatthe
beginningofthefunctionandterminatedattheendofthefunction.Staticstorage
durationcanbeobtainedbyplacingthekeywordstaticinfrontofthevariable
declaration.Thiscausesthevariable'sspacetobeallocatedwhentheprogramstarts
upandiskeptduringthelifeoftheprogram.Thevalueofthevariableispreserved
duringsubsequentcallstothefunctionthatdefinesit.Variableswithfilescopeare
automaticallystaticvariables.
Avariableisdefinedbythefollowing:
storageclassspecifiertypespecifiervariablenames,...
Thestorageclassspecifiercanbeoneofthefollowing:
typedef Thesymbolname"variablename"becomesatypespecifieroftype"type
specifier".Novariableisactuallycreated,thisismerelyforconvenience.
extern Indicatesthatthevariableisdefinedoutsideofthecurrentfile.Thisbringsthe
variablesscopeintothecurrentscope.Novariableisactuallycreatedbythis.
static Causesavariablethatisdefinedwithinafunctiontobepreservedinsubsequent
callstothefunction.
auto Causesalocalvariabletohavealocallifetime(default).
register Requeststhatthevariablebeaccessedasquicklyaspossible.Thisrequestisnot
guaranteed.Normally,thevariable'svalueiskeptwithinaCPUregisterfor
maximumspeed.
Thetypespecifiercanbeoneofthefollowing:
void DefinesanemptyorNULLvaluewhosetypeisincomplete.
char, signed char Variableislargeenoughtostoreabasiccharacterinthecharacterset.
Thevalueiseithersignedornonnegative.
unsigned char Sameaschar,butunsignedvaluesonly.
short, signed Definesashortsignedinteger.Maybethesamerangeasanormal
short, short int,
signed short int int,orhalfthebitsofanormalint.
unsigned short, Definesanunsignedshortinteger.
unsigned short int
int, signed, Definesasignedinteger.Ifnotypespecifierisgiven,thenthisisthe
signed int, or no default.
type specifier
unsigned int, Sameasint,butunsignedvaluesonly.
unsigned
long, signed long, Definesalongsignedinteger.Maybetwicethebitsizeasanormal
long int, signed
long int int,orthesameasanormalint.
unsigned long, Sameaslong,butunsignedvaluesonly.
unsigned long int
float Afloatingpointnumber.Consistsofasign,amantissa(number
greaterthanorequalto1),andanexponent.Themantissaistakento
thepoweroftheexponentthengiventhesign.Theexponentisalso
signedallowingextremelysmallfractions.Themantissagivesita
finiteprecision.
double Amoreaccuratefloatingpointnumberthanfloat.Normallytwiceas
manybitsinsize.
long double Increasesthesizeofdouble.
Herearethemaximumandminimumsizesofthetypespecifiersonmostcommon
implementations.Note:someimplementationsmaybedifferent.
Type Size Range
unsigned 8bits 0to255
char
char 8bits 128to127
unsigned int 16 0to65,535
bits
short int 16 32,768to32,767
bits
int 16 32,768to32,767
bits
unsigned 32 0to4,294,967,295
long
bits
long 32 2,147,483,648to2,147,483,647
bits
float 32 1.17549435*(10^38)to3.40282347*(10^+38)
bits
double 64 2.2250738585072014*(10^308)to1.7976931348623157*
bits (10^+308)
long double 80 3.4*(10^4932)to1.1*(10^4932)
bits

Examples:

int bob=32;
Createsvariable"bob"andinitializesittothevalue32.

char loop1,loop2,loop3='\x41';
Createsthreevariables.Thevalueof"loop1"and"loop2"isundefined.Thevalueof
loop3istheletter"A".

typedef char boolean;


Causesthekeyword"boolean"torepresentvariabletype"char".

boolean yes=1;
Createsvariable"yes"astype"char"andsetsitsvalueto1.

1.2.3EnumeratedTags

Enumerationallowsaseriesofconstantintegerstobeeasilyassigned.Theformatto
createaenumerationspecifieris:
enumidentifier{enumeratorlist};
Identifierisahandleforidentification,andisoptional.
Enumeratorlistisalistofvariablestobecreated.Theywillbeconstantintegers.
Eachvariableisgiventhevalueofthepreviousvariableplus1.Thefirstvariableis
giventhevalueof0.
Examples:
enum {joe, mary, bob, fran};
Creates4variables.Thevalueofjoeis0,maryis1,bobis2,andfranis3.

enum test {larry, floyd=20, ted};


Creates3variableswiththeidentifiertest.Thevalueoflarryis0,floydis20,andted
is21.

1.2.4Arrays

Arrayscreatesingleormultidimensionalmatrices.Theyaredefinedbyappendingan
integerencapsulatedinbracketsattheendofavariablename.Eachadditionalsetof
bracketsdefinesanadditionaldimensiontothearray.Whenaddressinganindexin
thearray,indexingbeginsat0andendsat1lessthanthedefinedarray.Ifnoinitial
valueisgiventothearraysize,thenthesizeisdeterminedbytheinitializers.When
definingamultidimensionalarray,nestedcurlybracescanbeusedtospecifywhich
dimensionofthearraytoinitialize.Theoutermostnestofcurlybracesdefinesthe
leftmostdimension,andworksfromlefttoright.
Examples:
int x[5];
Defines5integersstartingatx[0],andendingatx[4].Theirvaluesareundefined.

char str[16]="Blueberry";
Createsastring.Thevalueatstr[8]isthecharacter"y".Thevalueatstr[9]isthenull
character.Thevaluesfromstr[10]tostr[15]areundefined.

char s[]="abc";
Dimensionsthearrayto4(justlongenoughtoholdthestringplusanullcharacter),
andstoresthestringinthearray.

int y[3]={4};
Setsthevalueofy[0]to4andy[1]andy[2]to0.
int joe[4][5]={
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15}
};
Thefirstrowinitializesjoe[0],thesecondrowjoe[1]andsoforth.joe[3]isinitialized
to5zeros.

Thesameeffectisachievedby:
int joe[4][5]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

1.2.5StructuresandUnions

Structuresandunionsprovideawaytogroupcommonvariablestogether.Todefine
astructureuse:
struct structure-name {

variables,...

} structure-variables,...;

Structurenameisoptionalandnotneededifthestructurevariablesaredefined.
Insideitcancontainanynumberofvariablesseparatedbysemicolons.Atthe
end,structurevariablesdefinestheactualnamesoftheindividualstructures.
Multiplestructurescanbedefinedbyseparatingthevariablenameswithcommas.If
nostructurevariablesaregiven,novariablesarecreated.Structurevariablescanbe
definedseparatelybyspecifying:

structstructurenamenewstructurevariable;
newstructurevariablewillbecreatedandhasaseparateinstanceofallthevariables
instructurename.

Toaccessavariableinthestructure,youmustusearecordselector(.).

Unionsworkinthesamewayasstructuresexceptthatallvariablesarecontainedin
thesamelocationinmemory.Enoughspaceisallocatedforonlythelargestvariable
intheunion.Allothervariablesmustsharethesamememorylocation.Unionsare
definedusingtheunionkeyword.
Examples:
struct my-structure {
int fred[5];
char wilma, betty;
float barny=1;
};
Thisdefinesthestructuremystructure,butnothinghasyetbeendone.

struct my-structure account1;


Thiscreatesaccount1andithasallofthevariablesfrommystructure.
account1.barnycontainsthevalue"1".
union my-union {
char character_num;
int integer_num;
long long_num;
float float_num;
double double_num;
} number;
Thisdefinestheunionnumberandallocatesjustenoughspaceforthevariable
double_num.

number.integer_num=1;
Setsthevalueofinteger_numto"1".
number.float_num=5;
Setsthevalueoffloat_numto"5".
printf("%i",integer_num);
Thisisundefinedsincethelocationofinteger_numwasoverwrittenintheprevious
linebyfloat_num.

1.2.6Constants

Constantsprovideawaytodefineavariablewhichcannotbemodifiedbyanyother
partinthecode.Constantscanbedefinedbyplacingthekeywordconstinfrontof
anyvariabledeclaration.Ifthekeywordvolatileisplacedafterconst,thenthisallows
externalroutinestomodifythevariable(suchashardwaredevices).Thisalsoforces
thecompilertoretrievethevalueofthevariableeachtimeitisreferencedrather
thanpossiblyoptimizingitinaregister.
Constantnumberscanbedefinedinthefollowingway:
Hexadecimalconstant:
0xhexadecimaldigits...
WherehexadecimaldigitsisanydigitoranyletterAthroughForathroughf.
Decimalconstant:
Anynumberwherethefirstnumberisnotzero.
Octalconstant:
Anynumberwherethefirstnumbermustbezero.
Floatingconstant:
Afractionalnumber,optionallyfollowedbyeithereorEthentheexponent.
Thenumbermaybesuffixedby:
Uoru:
Causesthenumbertobeanunsignedlonginteger.
L orl:
Ifthenumberisafloatingpointnumber,thenitisalongdouble,otherwiseitisan
unsignedlonginteger.
Forf:
Causesthenumbertobeafloatingpointnumber.
Examples:
const float PI=3.141;
CausesthevariablePItobecreatedwithvalue3.141.Anysubsequentattemptsto
writetoPIarenotallowed.

const int joe=0xFFFF;


Causesjoetobecreatedwiththevalueof65535decimal.

const float penny=7.4e5;


Causespennytobecreatedwiththevalueof740000.000000.

1.2.7Strings

Stringsaresimplyanarrayofcharactersencapsulatedindoublequotes.Attheend
ofthestringanullcharacterisappended.
Examples:
"\x41"and"A"arethesamestring.

char fred[25]="He said, \"Go away!\"";


Thevalueatfred[9]isadoublequote.Thevalueatfred[20]isthenullcharacter.
Astringisanarrayofcharacter.Stringsmusthavea0ornullcharacterafterthelast
charactertoshowwherethestringends.Thenullcharacterisnotincludedinthe
string.
Thereare2waysofusingstrings.Thefirstiswithacharacterarrayandthesecondis
withastringpointer.
Acharacterarrayisdeclaredinthesamewayasanormalarray.
char ca[10];
Youmustsetthevalueofeachindividualelementofthearraytothecharacteryou
wantandyoumustmakethelastcharactera0.Remembertouse%swhenprinting
thestring.

char ca[10];
ca[0] = H;
ca[1] = E;
ca[2] = L;
ca[3] = L;
ca[4] = O;
ca[5] = 0;
printf(%s,ca);

Stringpointersaredeclaredasapointertoachar.
char *sp;
Whenyouassignavaluetothestringpointeritwillautomaticallyputthe0inforyou
unlikecharacterarrays.

char *sp;
sp = Hello;
printf(%s,sp);

Youcanreadastringintoonlyacharacterarrayusingscanfandnotastringpointer.
Ifyouwanttoreadintoastringpointerthenyoumustmakeitpointtoacharacter
array.

char ca[10], *sp;


scanf(%s, ca);
sp = ca;
scanf(%s, sp);

1.2.7.0Stringhandlingfunctions
Thestrings.hheaderfilehassomeusefulfunctionforworkingwithstrings.Hereare
someofthefunctionsyouwillusemostoften:

1.2.7.1strcpy(destination,source)
Youcantjustusestring1=string2inC.Youhavetousethestrcpyfunctiontocopy
onestringtoanother.strcpycopiesthesourcestringtothedestinationstring.
s1 = abc;
s2 = xyz;
strcpy( s1, s2 ); // s1 = xyz
1.2.7.2strcat(destination,source)
Joinsthedestinationandsourcestringsandputsthejoinedstringintothe
destinationstring.
s1 = abc;
s2 = xyz;
strcat( s1 , s2 ); // s1 = abcxyz
1.2.7.3strcmp(first,second)
Comparethefirstandsecondstrings.Ifthefirststringisgreatherthanthesecond
onethenanumberhigherthan0isreturned.Ifthefirststringislessthenthesecond
thenanumberlowerthan0isreturned.Ifthestringareequalthen0isreturned.
s1 = abc;
s2 = abc;
i = strcmp( s1 , s2 ); // i = 0

1.2.7.4strlen(string)
Returntheamountofcharacterinastring.
s = abcde;
i = strlen( s ); // i = 5
1.2.8sizeofKeyword

Declaration:
size_t sizeofexpression
or
size_t sizeof (type)
Thesizeofkeywordreturnsthenumberofbytesofthegivenexpressionortype.
size_tisanunsignedintegerresult.
Example:
printf("The number of bytes in an int is %d.\n",sizeof(int));

1.3.1FunctionDefinition

Afunctionisdeclaredinthefollowingmanner:
returntypefunctionname(parameterlist,...){body...}
returntypeisthevariabletypethatthefunctionreturns.Thiscannotbeanarray
typeorafunctiontype.Ifnotgiven,thenintisassumed.
functionnameisthenameofthefunction.
parameterlististhelistofparametersthatthefunctiontakesseparatedbycommas.
Ifnoparametersaregiven,thenthefunctiondoesnottakeanyandshouldbe
definedwithanemptysetofparenthesisorwiththekeywordvoid.Ifnovariabletype
isinfrontofavariableintheparamaterlist,thenintisassumed.Arraysandfunctions
arenotpassedtofunctions,butareautomaticallyconvertedtopointers.Ifthelistis
terminatedwithanellipsis(,...),thenthereisnosetnumberofparameters.Note:the
headerstdarg.hcanbeusedtoaccessargumentswhenusinganellipsis.
Ifthefunctionisaccessedbeforeitisdefined,thenitmustbeprototypedsothe
compilerknowsaboutthefunction.Prototypingnormallyoccursatthebeginningof
thesourcecode,andisdoneinthefollowingmanner:
returntypefunctionname(paramatertypelist);
returntypeandfunctionnamemustcorrespondexactlytotheactualfunction
definition.parametertypelistisalistseparatedbycommasofthetypesofvariable
parameters.Theactualnamesoftheparametersdonothavetobegivenhere,
althoughtheymayforthesakeofclarity.
Examples:
int joe(float, double, int);
Thisdefinestheprototypeforfunctionjoe.
int joe(float coin, double total, int sum)
{
/*...*/
}
Thisistheactualfunctionjoe.

int mary(void), *lloyd(double);


Thisdefinestheprototypeforthefunctionmarywithnoparametersandreturntype
int.Functionllyodisdefinedwithadoubletypeparamaterandreturnsapointerto
anint.

int (*peter)();
Definespeterasapointertoafunctionwithnoparametersspecified.Thevalueof
petercanbechangedtorepresentdifferentfunctions.

int (*aaron(char *(*)(void)) (long, int);


Definesthefunctionaaronwhichreturnsapointertoafunction.Thefunctionaaron
takesoneargument:apointertoafunctionwhichreturnsacharacterpointerand
takesnoarguments.Thereturnedfunctionreturnsatypeintandhastwo
parametersoftypelongandint.

1.3.2ProgramStartup

Aprogrambeginsbycallingthefunctionmain.Thereisnoprototyperequiredfor
this.Itcanbedefinedwithnoparameterssuchas:
int main(void){body...}
Orwiththefollowingtwoparameters:
int main(int argc, char *argv[]){body...}
Notethattheydonothavetobecalledargcorargv,butthisisthecommonnaming
system.
argcisanonnegativeinteger.Ifargcisgreaterthanzero,thenthestringpointedto
byargv[0]isthenameoftheprogram.Ifargcisgreaterthanone,thenthestrings
pointedtoby argv[1] throughargv[argc-1]aretheparameterspassedtothe
programbythesystem.
Example:

#include<stdio.h>

int main(int argc, char *argv[])


{
int loop;

if(argc>0)
printf("My program name is %s.\n",argv[0]);
if(argc>1)
{
for(loop=1;loop<argc;loop++)
printf("Parameter #%i is %s.\n",loop,argv[loop]);
}
}

1.4.1PointersandtheAddressOperator

Pointersarevariablesthatcontainthememoryaddressforanothervariable.A
pointerisdefinedlikeanormalvariable,butwithanasteriskbeforethevariable
name.Thetypespecifierdetermineswhatkindofvariablethepointerpointstobut
doesnotaffecttheactualpointer.
Theaddressoperatorcausesthememoryaddressforavariabletobereturned.Itis
writtenwithanampersandsignbeforethevariablename.
Whenusingapointer,referencingjustthepointersuchas:
int *my_pointer;
int barny;
my_pointer=&barny;
Causesmy_pointertocontaintheaddressofbarny.Nowthepointercanbeuse
indirectiontoreferencethevariableitpointsto.Indirectionisdonebyprefixingan
asterisktothepointervariable.
*my_pointer=3;
Thiscausesthevalueofbarnytobe3.Notethatthevalueofmy_pointerisunchanged.
Pointersofferanadditionalmethodforaddressinganarray.Thefollowingarray:
int my_array[3];
Canbeaddressednormallysuchas:
my_array[2]=3;
Thesamecanbeaccomplishedwith:
*(my_array+2)=3;
Notethatmy_arrayisapointerconstant.Itsvaluecannotbemodifiedsuchas:
my_array++;Thisisillegal.
However,ifapointervariableiscreatedsuchas:
int *some_pointer=my_array;
Thenmodifyingthepointerwillcorrectlyincrementthepointersoastopointtothe
nextelementinthearray.
*(some_pointer+1)=3;
Thiswillcausethevalueofmy_array[1]tobe3.Onasystemwhereaninttakesup
twobytes,adding1tosome_pointerdidnotactuallyincreaseitby1,butby2sothat
itpointedtothenextelementinthearray.
Functionscanalsoberepresentedwithapointer.Afunctionpointerisdefinedinthe
samewayasafunctionprototype,butthefunctionnameisreplacedbythepointer
nameprefixedwithanasteriskandencapsulatedwithparenthesis.Suchas:
int (*fptr)(int, char);
fptr=some_function;
To call this function:
(*ftpr)(3,'A');
Thisisequivalentto:
some_function(3,'A');
Astructureorunioncanhaveapointertorepresentit.Suchas:
struct some_structure homer;
struct some_structure *homer_pointer;
homer_pointer=&homer;
Thisdefineshomer_pointertopointtothestructurehomer.Now,whenyouusethe
pointertoreferencesomethinginthestructure,therecordselectornowbecomes
>insteadofaperiod.

homer_pointer->an_element=5;
Thisisthesameas:
homer.an_element=5;
Thevoidpointercanrepresentanunknownpointertype.
void *joe;
Thisisapointertoanundeterminedtype.

1.4.2Typecasting

Typecastingallowsavariabletoactlikeavariableofanothertype.Themethodof
typecastingisdonebyprefixingthevariabletypeenclosedbyparenthesisbeforethe
variablename.Theactualvariableisnotmodified.
Example:
float index=3; int loop=(int)index;
Thiscausesindextobetypecastedtoactlikeanint.

1.5.1Postfix

Postfixoperatorsareoperatorsthataresuffixedtoanexpression.
operand++;
Thiscausesthevalueoftheoperandtobereturned.Aftertheresultisobtained,the
valueoftheoperandisincrementedby1.
operand--;
Thisisthesamebutthevalueoftheoperandisdecrementedby1.
Examples:
int joe=3;
joe++;Thevalueofjoeisnow4.

printf("%i",joe++);
Thisoutputsthenumber4.Thevalueofjoeisnow5.

1.5.2UnaryandPrefix

Prefixoperatorsareoperatorsthatareprefixedtoanexpression.
++operand;
Thiscausesthevalueoftheoperandtobeincrementedby1.Itsnewvalueisthen
returned.
--operand;
Thisisthesamebutthevalueoftheoperandisdecrementedby1.
!operand
ReturnsthelogicalNOToperationontheoperand.Atrueoperandreturnsfalse,a
falseoperandreturnstrue.Alsoknownasthebangoperand.
~operand
Returnsthecomplimentoftheoperand.Thereturnedvalueistheoperandwithits
bitsreversed(1'sbecome0's,0'sbecome1's).
Examples:
int bart=7;
printf("%i",--bart);
Thisoutputsthenumber6.Thevalueofbartisnow6.

int lisa=1;
printf("%i",!lisa);
Thisoutputs0(false).

1.5.3Normal

Thereareseveralnormaloperatorswhichreturntheresultdefinedforeach:
expression1 + expression
Theresultofthisisthesumofthetwoexpressions.

expression1 - expression2
Theresultofthisisthevalueofexpression2subtractedfromexpression1.

expression1 * expression2
Theresultofthisisthevalueofexpression1multipliedbyexpression2.

expression1 / expression2
Theresultofthisisthevalueofexpression1dividedbyexpression2.

expression1 % expression2
Theresultofthisisthevalueoftheremainderafter
dividingexpression1byexpression2.Alsocalledthemodulooperator.

expression1 & expression2


ReturnsabitwiseANDoperationdoneonexpression1andexpression2.Theresultis
avaluethesamesizeastheexpressionswithitsbitsmodifiedusingthefollowing
rules:Bothbitsmustbe1(on)toresultin1(on),otherwisetheresultis0(off).

e1 e2 Result
0 0 0
0 1 0
1 0 0
1 1 1

expression1 | expression2
ReturnsabitwiseORoperationdoneonexpression1andexpression2.Theresultisa
valuethesamesizeastheexpressionswithitsbitsmodifiedusingthefollowing
rules:Bothbitsmustbe0(off)toresultin0(off),otherwisetheresultis1(on).
e1 e2 Result
0 0 0
0 1 1
1 0 1
1 1 1

expression1 ^ expression2
ReturnsabitwiseXORoperationdoneonexpression1andexpression2.Theresultisa
valuethesamesizeastheexpressionswithitsbitsmodifiedusingthefollowing
rules:Ifbothbitsarethesame,thentheresultis0(off),otherwisetheresultis1
(on).
e1 e2 Result
0 0 0
0 1 1
1 0 1
1 1 0

expression1 >> shift_value


Returnsexpression1withitsbitsshiftedtotherightbytheshift_value.Theleftmost
bitsarereplacedwithzerosifthevalueisnonnegativeorunsigned.Thisresultisthe
integerpartofexpression1dividedby2raisedtothepowerofshift_value.
Ifexpression1issigned,thentheresultisimplementationspecific.

expression1 << shift_value


Returnsexpression1withitsbitsshiftedtotheleftbytheshift_value.Therightmost
bitsarereplacedwithzeros.Thisresultisthevalueofexpression1multipliedbythe
valueof2raisedtothepowerofshift_value.Ifexpression1issigned,thentheresult
isimplementationspecific.

1.5.4Boolean

Thebooleanoperatorsreturneither1(true)or0(false).
expression1 && expression2
ReturnsthelogicalANDoperationofexpression1andexpression2.Theresultis1
(true)ifbothexpressionsaretrue,otherwisetheresultis0(false).
e1 e2 Result
0 0 0
0 1 0
1 0 0
1 1 1

expression1 || expression2
ReturnsthelogicalORoperationofexpression1andexpression2.Theresultis0
(false)ifbotherexpressionsarefalse,otherwisetheresultis1(true).
e1 e2 Result
0 0 0
0 1 1
1 0 1
1 1 1

expression1 < expression2


Returns1(true)ifexpression1islessthanexpression2,otherwisetheresultis0
(false).

expression1 > expression2


Returns1(true)ifexpression1isgreaterthanexpression2,otherwisetheresultis0
(false).

expression1 <= expression2


Returns1(true)ifexpression1islessthanorequaltoexpression2,otherwisethe
resultis0(false).

expression1 >= expression2


Returns1(true)ifexpression1isgreaterthanorequaltoexpression2,otherwisethe
resultis0(false).

expression1 == expression2
Returns1(true)ifexpression1isequaltoexpression2,otherwisetheresultis0
(false).

expression1 != expression2
Returns1(true)ifexpression1isnotequaltoexpression2,otherwisetheresultis0
(false).

1.5.5Assignment

Anassignmentoperatorstoresthevalueoftherightexpressionintotheleft
expression.
expression1 = expression2
Thevalueofexpression2isstoredinexpression1.

expression1 *= expression2
Thevalueofexpression1timesexpression2isstoredinexpression1.

expression1 /= expression2
Thevalueofexpression1dividedbyexpression2isstoredinexpression1.

expression1 %= expression2
Thevalueoftheremainderofexpression1dividedbyexpression2isstored
inexpression1.

expression1 += expression2
Thevalueofexpression1plusexpression2isstoredinexpression1.

expression1 -= expression2
Thevalueofexpression1minusexpression2isstoredinexpression1.

expression1 <<= shift_value


Thevalueofexpression1'sbitsareshiftedtotheleftbyshift_valueandstored
inexpression1.

expression1 >>= shift_value


Thevalueofexpression1'sbitsareshiftedtotherightbyshift_valueandstored
inexpression1.

expression1 &= expression2


ThevalueofthebitwiseANDofexpression1andexpression2isstoredinexpression1.
e1 e2 Result
0 0 0
0 1 0
1 0 0
1 1 1

expression1 ^= expression2
ThevalueofthebitwiseXORofexpression1andexpression2isstoredinexpression1.
e1 e2 Result
0 0 0
0 1 1
1 0 1
1 1 0

expression1 |= expression2
ThevalueofthebitwiseORofexpression1andexpression2isstoredinexpression1.
e1 e2 Result
0 0 0
0 1 1
1 0 1
1 1 1

1.5.6Precedence

Theoperatorshaveasetorderofprecedenceduringevaluation.Itemsencapsulated
inparenthesisareevaluatedfirstandhavethehighestprecedence.Thefollowing
chartshowstheorderofprecedencewiththeitemsatthetophavinghighest
precedence.
Operator Name
! LogicalNOT.Bang.
++ -- Incrementanddecrementoperators.
* / % Multiplicativeoperators.
+ - Additiveoperators.
<< >> Shiftoperators.
< > <= >= Inequalitycomparators.
== != Equalitycomparators
& BitwiseAND.
^ BitwiseXOR.
| BitwiseOR.
&& LogicalAND.
|| LogicalOR.
?: Conditional.
= op= Assignment.
Examples:
17 * 5 + !(1+1) && 0
Evaluatesto0(false).
5+7<4
Evaluatesto1(true).
a<b<c
Sameas(a<b)<c.

1.6.1if

Theifstatementevaluatesanexpression.Ifthatexpressionistrue,thenastatement
isexecuted.Ifanelseclauseisgivenandiftheexpressionisfalse,thentheelse's
statementisexecuted.
Syntax:
if( expression ) statement1;

or

if( expression ) statement1;


else statement2 ;

Examples:

if(loop<3) counter++;

if(x==y)
x++;
else
y++;

if(z>x)
{
z=5;
x=3;
}
else
{
z=3;
x=5;
}
1.6.2switch

Aswitchstatementallowsasinglevariabletobecomparedwithseveralpossible
constants.Ifthevariablematchesoneoftheconstants,thenaexecutionjumpis
madetothatpoint.Aconstantcannotappearmorethanonce,andtherecanonly
beonedefaultexpression.

Syntax:

switch ( variable )
{
case const:
statements...;
default:
statements...;
}

Examples:

switch(betty)
{
case 1:
printf("betty=1\n");
case 2:
printf("betty=2\n");
break;
case 3:
printf("betty=3\n");
break;
default:
printf("Not sure.\n");
}
Ifbettyis1,thentwolinesareprinted:betty=1andbetty=2.Ifbettyis2,thenonly
onelineisprinted:betty=2.Ifbetty=3,thenonlyonelineisprinted:betty=3.Ifbetty
doesnotequal1,2,or3,then"Notsure."isprinted.

1.6.3while

Thewhilestatementprovidesaniterativeloop.
Syntax:
while( expression ) statement...
statementisexecutedrepeatedlyaslongasexpressionistrue.Thetest
onexpressiontakesplacebeforeeachexecutionofstatement.
Examples:

while(*pointer!='j') pointer++;

while(counter<5)
{
printf("counter=%i",counter);
counter++;
}

1.6.4do

Thedo...whileconstructprovidesaniterativeloop.

Syntax:

do statement... while( expression );


statementisexecutedrepeatedlyaslongasexpressionistrue.Thetest
onexpressiontakesplaceaftereachexecutionofstatement.

Examples:

do {
betty++;
printf("%i",betty);
} while (betty<100);

1.6.5for

Theforstatementallowsforacontrolledloop.
Syntax:
for( expression1 ; expression2 ; expression3 ) statement...
expression1isevaluatedbeforethefirstiteration.Aftereachiteration,expression3is
evaluated.Bothexpression1andexpression3maybeommited.Ifexpression2is
ommited,itisassumedtobe1.statementisexecutedrepeatedlyuntilthevalue
ofexpression2is0.Thetestonexpression2occursbeforeeachexecution
ofstatement.
Examples:

for(loop=0;loop<1000;loop++)
printf("%i\n",loop);
Printsnumbers0through999.
for(x=3, y=5; x<100+y; x++, y--)
{
printf("%i\n",x);
some_function();
}
Printsnumbers3through53.some_functioniscalled51times.

1.6.6goto

Thegotostatementtransfersprogramexecutiontosomelabelwithintheprogram.
Syntax:
goto label;
....
label:
Examples:
goto skip_point;
printf("This part was skipped.\n");
skip_point:
printf("Hi there!\n");
Onlythetext"Hithere!"isprinted.

1.6.7continue

Thecontinuestatementcanonlyappearinaloopbody.Itcausestherestofthe
statementbodyinthelooptobeskipped.
Syntax:
continue;
Examples:
for(loop=0;loop<100;loop++)
{
if(loop==50)
continue;
printf("%i\n",loop);
}
Thenumbers0through99areprintedexceptfor50.
joe=0;
while(joe<1000)
{
for(zip=0;zip<100;zip++)
{
if(joe==500)
continue;
printf("%i\n",joe);
}
joe++;
}
Eachnumberfrom0to999isprinted100timesexceptforthenumber500whichis
notprintedatall.

1.6.8break

Thebreakstatementcanonlyappearinaswitchbodyoraloopbody.Itcausesthe
executionofthecurrentenclosingswitchorloopbodytoterminate.
Syntax:
break;
Examples:

switch(henry)
{
case 1: print("Hi!\n");
break;
case 2: break;
}
Ifhenryisequalto2,nothinghappens.
for(loop=0;loop<50;loop++)
{
if(loop==10)
break;
printf("%i\n",loop);
}
Onlynumbers0through9areprinted.

1.6.9return

Thereturnstatementcausesthecurrentfunctiontoterminate.Itcanreturnavalue
tothecallingfunction.Areturnstatementcannotappearinafunctionwhosereturn
typeisvoid.Ifthevaluereturnedhasatypedifferentfromthatofthefunction's
returntype,thenthevalueisconverted.Usingthereturnstatementwithoutan
expressioncreatesanundefinedresult.Reachingthe}attheendofthefunctionis
thesameasreturningwithoutanexpression.
Syntax:
return expression;
Examples:

int alice(int x, int y)


{
if(x<y)
return(1);
else
return(0);
}

1.7.1#if,#elif,#else,#endif

Thesepreprocessingdirectivescreateconditionalcompilingparametersthatcontrol
thecompilingofthesourcecode.Theymustbeginonaseparateline.
Syntax:
#if constant_expression
#else
#endif

or

#if constant_expression
#elif constant_expression
#endif
Thecompileronlycompilesthecodeafterthe#ifexpressionif
theconstant_expressionevaluatestoanonzerovalue(true).Ifthevalueis0
(false),thenthecompilerskipsthelinesuntilthenext#else, #elif,or#endif.If
thereisamatching#else,andtheconstant_expressionevaluatedto0(false),
thenthelinesbetweenthe#elseandthe#endifarecompiled.Ifthereisa
matching#elif,andthepreceding#ifevaluatedtofalse,then
theconstant_expressionafterthatisevaluatedandthecodebetweenthe#elifand
the#endifiscompiledonlyifthisexpressionevaluatestoanonzerovalue(true).
Examples:

int main(void)
{
#if 1
printf("Yabba Dabba Do!\n");
#else
printf("Zip-Bang!\n");
#endif
return 0;
}
Only"YabbaDabbaDo!"isprinted.
int main(void)
{
#if 1
printf("Checkpoint1\n");
#elif 1
printf("Checkpoint2\n");
#endif
return 0;
}
Only"Checkpoint1"isprinted.Notethatifthefirstlineis#if0,thenonly
"Checkpoint2"wouldbeprinted.
#if OS==1
printf("Version 1.0");
#elif OS==2
printf("Version 2.0");
#else
printf("Version unknown");
#endif
PrintsaccordingtothesettingofOSwhichisdefinedwitha#define.

1.7.2#define,#undef,#ifdef,#ifndef

Thepreprocessingdirectives#defineand#undefallowthedefinitionofidentifiers
whichholdacertainvalue.Theseidentifierscansimplybeconstantsoramacro
function.Thedirectives#ifdefand#ifndefallowconditionalcompilingofcertain
linesofcodebasedonwhetherornotanidentifierhasbeendefined.
Syntax:
#define identifier replacement-code

#undef identifier

#ifdef identifier
#else or #elif
#endif

#ifndef identifier
#else or #elif
#endif

#ifdefidentifieristhesameis#if defined( identifier).


#ifndefidentifieristhesameas#if !defined(identifier).
Anidentifierdefinedwith#defineisavailableanywhereinthesourcecodeuntil
a #undefisreached.
Afunctionmacrocanbedefinedwith#defineinthefollowingmanner:

#defineidentifier(parameterlist)(replacementtext)

Thevaluesintheparameterlistarereplacedinthereplacementtext.
Examples:
#define PI 3.141
printf("%f",PI);

#define DEBUG
#ifdef DEBUG
printf("This is a debug message.");
#endif

#define QUICK(x) printf("%s\n",x);


QUICK("Hi!")

#define ADD(x, y) x + y
z=3 * ADD(5,6)
Thisevaluatesto21duetothefactthatmultiplicationtakesprecedenceover
addition.
#define ADD(x,y) (x + y)
z=3 * ADD(5,6)
Thisevaluatesto33duetothefactthatthesummationisencapsulatedin
parenthesiswhichtakesprecedenceovermultiplication.

1.7.3#include

The#includedirectiveallowsexternalheaderfilestobeprocessedbythecompiler.
Syntax:
#include <header-file>

or
#include "source-file"
Whenenclosingthefilewith<and>,thentheimplementationsearchestheknown
headerdirectoriesforthefile(whichisimplementationdefined)andprocessesit.
Whenenclosedwithdoublequotationmarks,thentheentirecontentsofthesource
fileisreplacedatthispoint.Thesearchingmannerforthefileisimplementation
specific.
Examples:

#include <stdio.h>
#include "my_header.h"

1.7.4#line

The#linedirectiveallowsthecurrentlinenumberandtheapparentnameofthe
currentsourcecodefilenametobechanged.
Syntax:
#line line-number filename
Notethatifthefilenameisnotgiven,thenitstaysthesame.Thelinenumberonthe
currentlineisonegreaterthanthenumberofnewlinecharacters(sothefirstline
numberis1).
Examples:

#line 50 user.c

#line 23

1.7.5#error

The#errordirectivewillcausethecompilertohaltcompilingandreturnwiththe
specifiederrormessage.
Syntax:
#error message
Examples:

#ifndef VERSION
#error Version number not specified.
#endif

1.7.6#pragma

This#pragmadirectiveallowsadirectivetobedefined.Itseffectsare
implementationdefined.Ifthepragmaisnotsupported,thenitisignored.
Syntax:
#pragma directive

1.7.7PredefinedMacros

Thefollowingmacrosarealreadydefinedbythecompilerandcannotbechanged.

__LINE__ Adecimalconstantrepresentingthecurrentlinenumber.
__FILE__ Astringrepresentingthecurrentnameofthesourcecodefile.
__DATE__ Astringrepresentingthecurrentdatewhencompilingbeganforthecurrent
sourcefile.Itisintheformat"mmmddyyyy",thesameaswhatisgeneratedby
theasctimefunction.
__TIME__ Astringliteralrepresentingthecurrenttimewhencimpilingbeganforthecurrent
sourcefile.Itisintheformat"hh:mm:ss",thesameaswhatisgeneratedbythe
asctimefunction.
__STDC__ Thedecimalconstant1.UsedtoindicateifthisisastandardCcompiler.

2.1assert.h

Theassertheaderisusedfordebuggingpurposes.
Macros:
assert();
ExternalReferences:
NDEBUG
2.1.1assert
Declaration:
void assert(int expression);
Theassertmacroallowsdiagnosticinformationtobewrittentothestandarderror
file.
Ifexpressionevaluatesto0(false),thentheexpression,sourcecodefilename,and
linenumberaresenttothestandarderror,andthencallstheabortfunction.Ifthe
identifierNDEBUG ("nodebug")isdefinedwith#define NDEBUGthenthemacroassert
doesnothing.
Commonerroroutputtingisintheform:
Assertion failed: expression, file filename, line line-number
Example:

#include<assert.h>

void open_record(char *record_name)


{
assert(record_name!=NULL);
/* Rest of code */
}

int main(void)
{
open_record(NULL);
}

2.2ctype.h

Thectypeheaderisusedfortestingandconvertingcharacters.Acontrolcharacter
referstoacharacterthatisnotpartofthenormalprintingset.IntheASCIIcharacter
set,thecontrolcharactersarethecharactersfrom0(NUL)through0x1F(US),and
thecharacter0x7F(DEL).Printablecharactersarethosefrom0x20(space)to0x7E
(tilde).
Functions:
isalnum();
isalpha();
iscntrl();
isdigit();
isgraph();
islower();
isprint();
ispunct();
isspace();
isupper();
isxdigit();
tolower();
toupper();
2.2.1is...Functions
Declarations:
int isalnum(int character);
int isalpha(int character);
int iscntrl(int character);
int isdigit(int character);
int isgraph(int character);
int islower(int character);
int isprint(int character);
int ispunct(int character);
int isspace(int character);
int isupper(int character);
int isxdigit(int character);
Theis...functionstestthegivencharacterandreturnanonzero(true)resultifit
satisfiesthefollowingconditions.Ifnot,then0(false)isreturned.
Conditions:
isalnum aletter(AtoZoratoz)oradigit(0to9)
isalpha aletter(AtoZoratoz)
iscntrl anycontrolcharacter(0x00to0x1For0x7F)
isdigit adigit(0to9)
isgraph anyprintingcharacterexceptforthespacecharacter(0x21to0x7E)
islower alowercaseletter(atoz)
isprint anyprintingcharacter(0x20to0x7E)
ispunct anypunctuationcharacter(anyprintingcharacterexceptforspace
characterorisalnum)
isspace awhitespacecharacter(space,tab,carriagereturn,newline,vertical
tab,orformfeed)
isupper anuppercaseletter(AtoZ)
isxdigit ahexadecimaldigit(0to9,AtoF,oratof)
2.2.2to...Functions
Declarations:
int tolower(int character);
int toupper(int character);
Theto...functionsprovideameanstoconvertasinglecharacter.Ifthecharacter
matchestheappropriatecondition,thenitisconverted.Otherwisethecharacteris
returnedunchanged.
Conditions:
tolower Ifthecharacterisanuppercasecharacter(AtoZ),thenitisconvertedto
lowercase(atoz)
toupper Ifthecharacterisalowercasecharacter(atoz),thenitisconvertedto

uppercase(AtoZ)
Example:
#include<ctype.h>
#include<stdio.h>
#include<string.h>

int main(void)
{
int loop;
char string[]="THIS IS A TEST";

for(loop=0;loop<strlen(string);loop++)
string[loop]=tolower(string[loop]);

printf("%s\n",string);
return 0;
}

2.3errno.h

Theerrnoheaderisusedasageneralerrorhandler.
Macros:
EDOM
ERANGE
Variables:
errno
2.3.1EDOM
Declaration:
#define EDOM some_value
EDOMisanidentifiermacrodeclaredwith#define.Itsvaluerepresentsadomain
errorwhichisreturnedbysomemathfunctionswhenadomainerroroccurs.
2.3.2ERANGE
Declaration:
#define ERANGE some_value
ERANGEisanidentifiermacrodeclaredwith#define.Itsvaluerepresentsarangeerror
whichisreturnedbysomemathfunctionswhenarangeerroroccurs.
2.3.3errno
Declaration:
int errno;
Theerrnovariablehasavalueofzeroatthebeginningoftheprogram.Ifanerror
occurs,thenthisvariableisgiventhevalueoftheerrornumber.

2.4float.h

Thefloatheaderdefinestheminimumandmaximumlimitsoffloatingpointnumber
values.
2.4.1DefinedValues
Afloatingpointnumberisdefinedinthefollowingmanner:
signvalueEexponent
Wheresignisplusorminus,valueisthevalueofthenumber,andexponentisthe
valueoftheexponent.
Thefollowingvaluesaredefinedwiththe#define directive.Thesevaluesare
implementationspecific,butmaynotbeanylowerthanwhatisgivenhere.Note
thatinallinstancesFLTreferstotypefloat,DBLreferstodouble,andLDBLreferstolong
double.
Definesthewayfloatingpointnumbersarerounded.
1 indeterminable

0 towardzero
FLT_ROUNDS
1 tonearest

2 towardpositiveinfinity

3 towardnegativeinfinity

FLT_RADIX 2
Definesthebase(radix)representationoftheexponent(i.e.
base2isbinary,base10isthenormaldecimalrepresentation,
base16isHex).
FLT_MANT_DIG Definesthenumberofdigitsinthenumber(in
DBL_MANT_DIG
LDBL_MANT_DIG theFLT_RADIXbase).
FLT_DIG 6 Themaximumnumberdecimaldigits(base10)thatcanbe
DBL_DIG 10
LDBL_DIG 10 representedwithoutchangeafterrounding.
FLT_MIN_EXP Theminimumnegativeintegervalueforanexponentinbase
DBL_MIN_EXP
LDBL_MIN_EXP FLT_RADIX.
FLT_MIN_10_EXP -
37
DBL_MIN_10_EXP - Theminimumnegativeintegervalueforanexponentinbase
37 10.
LDBL_MIN_10_EXP
-37
FLT_MAX_EXP
DBL_MAX_EXP ThemaximumintegervalueforanexponentinbaseFLT_RADIX.
LDBL_MAX_EXP
FLT_MAX_10_EXP
+37
DBL_MAX_10_EXP
+37 Themaximumintegervalueforanexponentinbase10.
LDBL_MAX_10_EXP
+37
FLT_MAX 1E+37
DBL_MAX 1E+37 Maximumfinitefloatingpointvalue.
LDBL_MAX 1E+37
FLT_EPSILON 1E-5
DBL_EPSILON 1E-9
LDBL_EPSILON 1E- Leastsignificantdigitrepresentable.
9
FLT_MIN 1E-37
DBL_MIN 1E-37 Minimumfloatingpointvalue.
LDBL_MIN 1E-37

2.5limits.h

Thelimitsheaderdefinesthecharacteristicsofvariabletypes.
2.5.1DefinedValues
Thefollowingvaluesaredefinedwiththe#definedirective.Thesevaluesare
implementationspecific,butmaynotbeanylowerthanwhatisgivenhere.
CHAR_BIT 8 Numberofbitsinabyte.
SCHAR_MIN - Minimumvalueforasignedchar.
127
SCHAR_MAX
+127 Maximumvalueforasignedchar.
UCHAR_MAX
255 Maximumvalueforanunsignedchar.
Thesedefinetheminimumandmaximumvaluesforachar.Ifa
CHAR_MIN charisbeingrepresentedasasignedinteger,thentheirvaluesare
CHAR_MAX thesameasthesignedchar(SCHAR)values.OtherwiseCHAR_MINis0
andCHAR_MAXisthesameasUCHAR_MAX.
MB_LEN_MAX 1 Maximumnumberofbytesinamultibytecharacter.
SHRT_MIN -
32767 Minimumvalueforashortint.
SHRT_MAX
+32767 Maximumvalueforashortint.
USHRT_MAX
65535 Maximumvalueforanunsignedshortint.
INT_MIN -
32767 Minimumvalueforanint.
INT_MAX
+32767 Maximumvalueforanint.
UINT_MAX
65535 Maximumvalueforanunsignedint.
LONG_MIN -
2147483647 Minimumvalueforalongint.
LONG_MAX
+2147483647 Maximumvalueforalongint.
ULONG_MAX
4294967295 Maximumvalueforanunsignedlongint.

2.6locale.h

Thelocaleheaderisusefulforsettinglocationspecificinformation.
Variables:
struct lconv
Macros:
NULL
LC_ALL
LC_COLLATE
LC_CTYPE
LC_MONETARY
LC_NUMERIC
LC_TIME
Functions:
localeconv();
setlocale();
2.6.1VariablesandDefinitions
Thelconvstructurecontainsthefollowingvariablesinanyorder.Theuseofthis
structureisdescribedin2.6.3localeconv.
char *decimal_point;
char *thousands_sep;
char *grouping;
char *int_curr_symbol;
char *currency_symbol;
char *mon_decimal_point;
char *mon_thousands_sep;
char *mon_grouping;
char *positive_sign;
char *negative_sign;
char int_frac_digits;
char frac_digits;
char p_cs_precedes;
char p_sep_by_space;
char n_cs_precedes;
char n_sep_by_space;
char p_sign_posn;
char n_sign_posn;
TheLC_macrosaredescribedin2.6.2setlocale.NULListhevalueofanullpointer
constant.
2.6.2setlocale
Declaration:
char *setlocale(int category, const char *locale);
Setsorreadslocationdependentinformation.
categorycanbeoneofthefollowing:
LC_ALL Seteverything.
LC_COLLATE Affectsstrcollandstrxfrmfunctions.
LC_CTYPE Affectsallcharacterfunctions.
LC_MONETARY Affectsthemonetaryinformationprovidedbylocaleconvfunction.
LC_NUMERIC Affectsdecimalpointformattingandtheinformationprovided
bylocaleconvfunction.
LC_TIME Affectsthestrftimefunction.
Avalueof"C"forlocalesetsthelocaletothenormalCtranslationenvironment
settings(default).Anullvalue("")setsthenativeenvironmentsettings.Anull
pointer(NULL)causessetlocaletoreturnapointertothestringassociatedwiththis
categoryforthecurrentsettings(nochangesoccur).Allothervaluesare
implementationspecific.
Afterasuccessfulset,setlocalereturnsapointertoastringwhichrepresentsthe
previouslocationsetting.OnfailureitreturnsNULL.
Example:
#include<locale.h>
#include<stdio.h>

int main(void)
{
char *old_locale;

old_locale=setlocale(LC_ALL,"C");
printf("The preivous setting was %s.\n",old_locale);
return 0;
}
2.6.3localeconv
Declaration:
struct lconv *localeconv(void);
Setsthestructurelconvtorepresentthecurrentlocationsettings.
Thestringpointersinthestructuremaypointtoanullstring("")whichindicatesthat
thevalueisnotavailable.Thechartypesarenonnegativenumbers.Ifthevalue
isCHAR_MAX,thenthevalueisnotavailable.
lconvvariables:
char Decimalpointcharacterusedfornonmonetaryvalues.
*decimal_point
char Thousandsplaceseparatorcharacterusedfornonmonetary
*thousands_sep
values.
char *grouping Astringthatindicatesthesizeofeachgroupofdigitsinnon
monetaryquantities.Eachcharacterrepresentsaninteger
valuewhichdesignatesthenumberofdigitsinthecurrent
group.Avalueof0meansthatthepreviousvalueistobe
usedfortherestofthegroups.
char Astringoftheinternationalcurrencysymbolsused.Thefirst
*int_curr_symbol
threecharactersarethosespecifiedbyISO4217:1987and
thefourthisthecharacterwhichseparatesthecurrency
symbolfromthemonetaryquantity.
char Thelocalsymbolusedforcurrency.
*currency_symbol
char Thedecimalpointcharacterusedformonetaryvalues.
*mon_decimal_point
char Thethousandsplacegroupingcharacterusedformonetary
*mon_thousands_sep
values.
char *mon_grouping Astringwhoseelementsdefinethesizeofthegroupingof
digitsinmonetaryvalues.Eachcharacterrepresentsan
integervaluewhichdesignatesthenumberofdigitsinthe
currentgroup.Avalueof0meansthatthepreviousvalueis
tobeusedfortherestofthegroups.
char Thecharacterusedforpositivemonetaryvalues.
*positive_sign
char Thecharacterusedfornegativemonetaryvalues.
*negative_sign
char Numberofdigitstoshowafterthedecimalpointin
int_frac_digits
internationalmonetaryvalues.
char frac_digits Numberofdigitstoshowafterthedecimalpointin
monetaryvalues.
char p_cs_precedes Ifequalto1,thenthe currency_symbol appearsbeforea
positivemonetaryvalue.Ifequalto0,then
thecurrency_symbolappearsafterapositivemonetaryvalue.
char Ifequalto1,thenthe currency_symbol isseparatedbya
p_sep_by_space
spacefromapositivemonetaryvalue.Ifequalto0,then
thereisnospacebetweenthecurrency_symbolandapositive
monetaryvalue.
char n_cs_precedes Ifequalto1,thenthe currency_symbol precedesanegative
monetaryvalue.Ifequalto0,thenthecurrency_symbol
succeeds a negative monetary value.
char Ifequalto1,thenthe currency_symbol isseparatedbya
n_sep_by_space
spacefromanegativemonetaryvalue.Ifequalto0,then
thereisnospacebetweenthecurrency_symbolanda
negativemonetaryvalue.
char p_sign_posn Representstheposition ofthe positive_signinapositive
monetaryvalue.
char n_sign_posn Representsthepositionofthe negative_signinanegative
monetaryvalue.
Thefollowingvaluesareusedforp_sign_posnandn_sign_posn:
0 Parenthesesencapsulatethevalueandthecurrency_symbol.

1 Thesignprecedesthevalueandcurrency_symbol.

2 Thesignsucceedsthevalueandcurrency_symbol.

3 Thesignimmediatelyprecedesthevalueandcurrency_symbol.

4 Thesignimmediatelysucceedsthevalueandcurrency_symbol.

Example:

#include<locale.h>
#include<stdio.h>
int main(void)
{
struct lconv locale_structure;
struct lconv *locale_ptr=&locale_structure;
locale_ptr=lcoaleconv();
printf("Decimal point: %s",locale_ptr->decimal_point);
printf("Thousands Separator: %s",locale_ptr->thousands_sep);
printf("Grouping: %s",locale_ptr->grouping);
printf("International Currency Symbol: %s",locale_ptr->int_curr_symbol);
printf("Currency Symbol: %s",locale_ptr->currency_symbol);
printf("Monetary Decimal Point: %s",locale_ptr-
>mon_decimal_point);
printf("Monetary Thousands Separator: %s",locale_ptr-
>mon_thousands_sep);
printf("Monetary Grouping: %s",locale_ptr->mon_grouping);
printf("Monetary Positive Sign: %s",locale_ptr->positive_sign);
printf("Monetary Negative Sign: %s",locale_ptr->negative_sign);
printf("Monetary Intl Decimal Digits: %c",locale_ptr->int_frac_digits);
printf("Monetary Decimal Digits: %c",locale_ptr->frac_digits);
printf("Monetary + Precedes: %c",locale_ptr->p_cs_precedes);
printf("Monetary + Space: %c",locale_ptr->p_sep_by_space);
printf("Monetary - Precedes: %c",locale_ptr->n_cs_precedes);
printf("Monetary - Space: %c",locale_ptr->n_sep_by_space);
printf("Monetary + Sign Posn: %c",locale_ptr->p_sign_posn);
printf("Monetary - Sign Posn: %c",locale_ptr->n_sign_posn);
}

2.7math.h

Themathheaderdefinesseveralmathematicfunctions.
Macros:
HUGE_VAL
Functions:
acos();
asin();
atan();
atan2();
ceil();
cos();
cosh();
exp();
fabs();
floor();
fmod();
frexp();
ldexp();
log();
log10();
modf();
pow();
sin();
sinh();
sqrt();
tan();
tanh();
2.7.1ErrorConditions
Allmath.hfunctionshandleerrorssimilarly.
Inthecasethattheargumentpassedtothefunctionexceedstherangeofthat
function,thenthevariableerrnoissettoEDOM.Thevaluethatthefunctionreturnsis
implementationspecific.
Inthecasethatthevaluebeingreturnedistoolargetoberepresentedinadouble,
thenthefunctionreturnsthemacroHUGE_VAL,andsetsthe
variableerrnotoERANGEtorepresentanoverflow.Ifthevalueistoosmalltobe
representedinadouble,thenthefunctionreturnszero.Inthiscasewhetheror
noterrnoissettoERANGEisimplementationspecific.
errno, EDOM,andERANGEaredefinedintheerrno.hheader.
Notethatinallcaseswhenitisstatedthatthereisnorangelimit,itisimpliedthat
thevalueislimitedbytheminimumandmaximumvaluesoftypedouble.
2.7.2TrigonometricFunctions
2.7.2.1acos
Declaration:
double acos(double x);
Returnsthearccosineofxinradians.
Range:
Thevaluexmustbewithintherangeof1to+1(inclusive).Thereturnedvalueisin
therangeof0topi(inclusive).
2.7.2.2asin
Declaration:
double asin(double x);
Returnsthearcsineofxinradians.
Range:
Thevalueofxmustbewithintherangeof1to+1(inclusive).Thereturnedvalueis
intherangeofp/2to+p/2(inclusive).
2.7.2.3atan
Declaration:
double atan(double x);
Returnsthearctangentofxinradians.
Range:
Thevalueofxhasnorange.Thereturnedvalueisintherangeofp/2to+p/2
(inclusive).
2.7.2.4atan2
Declaration:
double atan2(doubly y, double x);
Returnsthearctangentinradiansofy/xbasedonthesignsofbothvaluesto
determinethecorrectquadrant.
Range:
Bothyandxcannotbezero.Thereturnedvalueisintherangeofp/2to+p/2
(inclusive).
2.7.2.5cos
Declaration:
double cos(double x);
Returnsthecosineofaradiananglex.
Range:
Thevalueofxhasnorange.Thereturnedvalueisintherangeof1to+1(inclusive).
2.7.2.6cosh
Declaration:
double cosh(double x);
Returnsthehyperboliccosineofx.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.2.7sin
Declaration:
double sin(double x);
Returnsthesineofaradiananglex.
Range:
Thevalueofxhasnorange.Thereturnedvalueisintherangeof1to+1(inclusive).
2.7.2.8sinh
Declaration:
double sinh(double x);
Returnsthehyperbolicsineofx.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.2.9tan
Declaration:
double tan(double x);
Returnsthetangentofaradiananglex.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.2.10tanh
Declaration:
double tanh(double x);
Returnsthehyperbolictangentofx.
Range:
Thevalueofxhasnorange.Thereturnedvalueisintherangeof1to+1(inclusive).
2.7.3Exponential,Logarithmic,andPowerFunctions
2.7.3.1exp
Declaration:
double exp(double x);
Returnsthevalueoferaisedtothexthpower.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.3.2frexp
Declaration:
double frexp(double x, int *exponent);
Thefloatingpointnumberxisbrokenupintoamantissaandexponent.
Thereturnedvalueisthemantissaandtheintegerpointedtobyexponentisthe
exponent.Theresultantvalueisx=mantissa * 2^exponent.
Range:
Themantissaisintherangeof.5(inclusive)to1(exclusive).
2.7.3.3ldexp
Declaration:
double ldexp(double x, int exponent);
Returnsxmultipliedby2raisedtothepowerofexponent.
x*2^exponent
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.3.4log
Declaration:
double log(double x);
Returnsthenaturallogarithm(baseelogarithm)ofx.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.3.5log10
Declaration:
double log10(double x);
Returnsthecommonlogarithm(base10logarithm)ofx.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.3.6modf
Declaration:
double modf(double x, double *integer);
Breaksthefloatingpointnumberxintointegerandfractioncomponents.
Thereturnedvalueisthefractioncomponent(partafterthedecimal),and
setsintegertotheintegercomponent.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.3.7pow
Declaration:
double pow(double x, double y);
Returnsxraisedtothepowerofy.
Range:
xcannotbenegativeifyisafractionalvalue.xcannotbezeroifyislessthanor
equaltozero.
2.7.3.8sqrt
Declaration:
double sqrt(double x);
Returnsthesquarerootofx.
Range:
Theargumentcannotbenegative.Thereturnedvalueisalwayspositive.
2.7.4OtherMathFunctions
2.7.4.1ceil
Declaration:
double ceil(double x);
Returnsthesmallestintegervaluegreaterthanorequaltox.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.4.2fabs
Declaration:
double fabs(double x);
Returnstheabsolutevalueofx(anegativevaluebecomespositive,positivevalueis
unchanged).
Range:
Thereisnorangelimitontheargument.Thereturnvalueisalwayspositive.
2.7.4.3floor
Declaration:
double floor(double x);
Returnsthelargestintegervaluelessthanorequaltox.
Range:
Thereisnorangelimitontheargumentorreturnvalue.
2.7.4.4fmod
Declaration:
double fmod(double x, double y);
Returnstheremainderofxdividedbyy.
Range:
Thereisnorangelimitonthereturnvalue.Ifyiszero,theneitherarangeerrorwill
occurorthefunctionwillreturnzero(implementationdefined).

2.8setjmp.h

Thesetjmpheaderisusedforcontrollinglowlevelcallsandreturnstoandfrom
functions.
Macros:
setjmp();
Functions:
longjmp();
Variables:
typedef jmp_buf
2.8.1VariablesandDefinitions
Thevariabletype jmp_bufisanarraytypeusedforholdinginformation
forsetjmp andlongjmp.
2.8.2setjmp
Declaration:
int setjmp(jmp_buf environment);
Savestheenvironmentintothevariableenvironment.Ifanonzerovalueisreturned,
thenthisindicatesthatthepointinthesourcecodewasreachedbyalongjmp.
Otherwisezeroisreturnedindicatingtheenvironmenthasbeensaved.
2.8.3longjmp
Declaration:
void longjmp(jmp_buf environment, int value);
Causestheenvironmenttoberestoredfromasetjmpcallwheretheenvironment
variablehadbeensaved.Itcausesexecutiontogotothesetjmplocationas
ifsetjmphadreturnedthevalueofthevariablevalue.Thevariablevaluecannotbe
zero.However,ifzeroispassed,then1isreplaced.Ifthefunctionwheresetjmpwas
calledhasterminated,thentheresultsareundefined.
Example:
#include<setjmp.h>
#include<stdio.h>

void some_function(jmp_buf);

int main(void)
{
int value;
jmp_buf environment_buffer;

value=setjmp(environment_buffer);
if(value!=0)
{
printf("Reached this point from a longjmp with value=%d.\n",value);
exit(0);
}
printf("Calling function.\n");
some_function(environment_buffer);
return 0;
}

void some_function(jmp_buf env_buf)


{
longjmp(env_buf,5);
}
Theoutputfromthisprogramshouldbe:

Calling function.
Reached this point from a longjmp with value=5.

2.9signal.h

Thesignalheaderprovidesameanstohandlesignalsreportedduringaprogram's
execution.
Macros:
SIG_DFL
SIG_ERR
SIG_IGN
SIGABRT
SIGFPE
SIGILL
SIGINT
SIGSEGV
SIGTERM
Functions:
signal();
raise();
Variables:
typedef sig_atomic_t
2.9.1VariablesandDefinitions
Thesig_atomic_ttypeisoftypeintandisusedasavariableinasignalhandler.
TheSIG_macrosareusedwiththesignalfunctiontodefinesignalfunctions.
SIG_DFL Defaulthandler.
SIG_ERR Representsasignalerror.
SIG_IGN Signalignore.

TheSIGmacrosareusedtorepresentasignalnumberinthefollowingconditions:
SIGABRT Abnormaltermination(generatedbytheabortfunction).
SIGFPE Floatingpointerror(errorcausedbydivisionbyzero,invalidoperation,
etc.).
SIGILL Illegaloperation(instruction).
SIGINT Interactiveattentionsignal(suchasctrlC).
SIGSEGV Invalidaccesstostorage(segmentviolation,memoryviolation).
SIGTERM Terminationrequest.
2.9.2signal
Declaration:
void (*signal(int sig, void (*func)(int)))(int);
Controlshowasignalishandled.sigrepresentsthesignalnumbercompatiblewith
theSIGmacros.funcisthefunctiontobecalledwhenthesignaloccurs.Iffunc
isSIG_DFL,thenthedefaulthandleriscalled.IffuncisSIG_IGN,thenthesignalis
ignored.Iffuncpointstoafunction,thenwhenasignalisdetectedthedefault
functioniscalled(SIG_DFL),thenthefunctioniscalled.Thefunctionmusttakeone
argumentoftypeintwhichrepresentsthesignalnumber.Thefunctionmay
terminatewithreturn,abort,exit,orlongjmp.Whenthefunctionterminates
executionresumeswhereitwasinterrupted(unlessitwasaSIGFPEsignalinwhich
casetheresultisundefined).
Ifthecalltosignalissuccessful,thenitreturnsapointertotheprevioussignal
handlerforthespecifiedsignaltype.Ifthecallfails,thenSIG_ERRisreturned
anderrnoissetappropriately.
2.9.3raise
Declaration
int raise(int sig);
Causessignalsigtobegenerated.Thesigargumentiscompatiblewith
theSIGmacros.
Ifthecallissuccessful,zeroisreturned.Otherwiseanonzerovalueisreturned.
Example:
#include<signal.h>
#include<stdio.h>

void catch_function(int);

int main(void)
{
if(signal(SIGINT, catch_function)==SIG_ERR)
{
printf("An error occured while setting a signal handler.\n");
exit(0);
}

printf("Raising the interactive attention signal.\n");


if(raise(SIGINT)!=0)
{
printf("Error raising the signal.\n");
exit(0);
}
printf("Exiting.\n");
return 0;
}

void catch_function(int signal)


{
printf("Interactive attention signal caught.\n");
}
Theoutputfromtheprogramshouldbe(assumingnoerrors):

Raising the interactive attention signal.


Interactive attention signal caught.
Exiting.

2.10stdarg.h

Thestdargheaderdefinesseveralmacrosusedtogettheargumentsinafunction
whenthenumberofargumentsisnotknown.
Macros:
va_start();
va_arg();
va_end();
Variables:
typedef va_list
2.10.1VariablesandDefinitions
The va_listtypeisatypesuitableforuseinaccessingtheargumentsofafunction
withthestdargmacros.
Afunctionofvariableargumentsisdefinedwiththeellipsis(,...)attheendofthe
parameterlist.
2.10.2va_start
Declaration:
void va_start(va_list ap, last_arg);
Initializesapforusewiththeva_argandva_endmacros.last_argisthelastknown
fixedargumentbeingpassedtothefunction(theargumentbeforetheellipsis).
Notethatva_startmustbecalledbeforeusingva_argandva_end.
2.10.3va_arg
Declaration:
type va_arg(va_list ap, type);
Expandstothenextargumentintheparamaterlistofthefunctionwithtypetype.
Notethatapmustbeinitializedwithva_start.Ifthereisnonextargument,thenthe
resultisundefined.
2.10.4va_end
Declaration:
void va_end(va_list ap);
Allowsafunctionwithvariableargumentswhichusedtheva_startmacrotoreturn.
Ifva_endisnotcalledbeforereturningfromthefunction,theresultisundefined.The
variableargumentlistapmaynolongerbeusedafteracalltova_endwithoutacall
tova_start.
Example:
#include<stdarg.h>
#include<stdio.h>

void sum(char *, int, ...);

int main(void)
{
sum("The sum of 10+15+13 is %d.\n",3,10,15,13);
return 0;
}

void sum(char *string, int num_args, ...)


{
int sum=0;
va_list ap;
int loop;

va_start(ap,num_args);
for(loop=0;loop<num_args;loop++)
sum+=va_arg(ap,int);

printf(string,sum);
va_end(ap);
}

2.11stddef.h

Thestddefheaderdefinesseveralstandarddefinitions.Manyofthesedefinitions
alsoappearinotherheaders.
Macros:
NULL
offsetof();
Variables:
typedef ptrdiff_t
typedef size_t
typedef wchar_t
2.11.1VariablesandDefinitions
ptrdiff_t istheresultofsubtractingtwopointers.
size_t istheunsignedintegerresultofthesizeofkeyword.
wchar_t isanintegertypeofthesizeofawidecharacterconstant.
NULListhevalueofanullpointerconstant.
offsetof(type, member-designator)
Thisresultsinaconstantintegeroftypesize_t whichistheoffsetinbytesofa
structurememberfromthebeginningofthestructure.Thememberisgiven
bymemberdesignator,andthenameofthestructureisgivenintype.
Example:
#include<stddef.h>
#include<stdio.h>

int main(void)
{
struct user{
char name[50];
char alias[50];
int level;
};

printf("level is the %d byte in the user structure.\n"),


offsetof(struct user,level));
}
Theoutputshouldbe:

level is the 100 byte in the user structure.

2.12stdio.h

Thestdioheaderprovidesfunctionsforperforminginputandoutput.
Macros:
NULL
_IOFBF
_IOLBF
_IONBF
BUFSIZ
EOF
FOPEN_MAX
FILENAME_MAX
L_tmpnam
SEEK_CUR
SEEK_END
SEEK_SET
TMP_MAX
stderr
stdin
stdout
Functions:
clearerr();
fclose();
feof();
ferror();
fflush();
fgetpos();
fopen();
fread();
freopen();
fseek();
fsetpos();
ftell();
fwrite();
remove();
rename();
rewind();
setbuf();
setvbuf();
tmpfile();
tmpnam();
fprintf();
fscanf();
printf();
scanf();
sprintf();
sscanf();
vfprintf();
vprintf();
vsprintf();
fgetc();
fgets();
fputc();
fputs();
getc();
getchar();
gets();
putc();
putchar();
puts();
ungetc();
perror();
Variables:
typedef size_t
typedef FILE
typedef fpos_t
2.12.1VariablesandDefinitions
size_tistheunsignedintegerresultofthesizeofkeyword.
FILEisatypesuitableforstoringinformationforafilestream.
fpos_t isatypesuitableforstoringanypositioninafile.

NULListhevalueofanullpointerconstant.
_IOFBF,_IOLBF,and_IONBF areusedinthesetvbuffunction.
BUFSIZisanintegerwhichrepresentsthesizeofthebufferusedbythesetbuf
function.
EOFisanegativeintegerwhichindicatesanendoffilehasbeenreached.
FOPEN_MAX isanintegerwhichrepresentsthemaximumnumberoffilesthatthe
systemcanguaranteethatcanbeopenedsimultaneously.
FILENAME_MAX isanintegerwhichrepresentsthelongestlengthofachararray
suitableforholdingthelongestpossiblefilename.Iftheimplementationimposesno
limit,thenthisvalueshouldbetherecommendedmaximumvalue.
L_tmpnamisanintegerwhichrepresentsthelongestlengthofachararraysuitable
forholdingthelongestpossibletemporaryfilenamecreatedbythetmpnam
function.
SEEK_CUR,SEEK_END,andSEEK_SET areusedinthefseekfunction.
TMP_MAX isthemaximumnumberofuniquefilenamesthatthefunctiontmpnamcan
generate.
stderr,stdin,andstdoutarepointerstoFILEtypeswhichcorrespondtothestandard
error,standardinput,andstandardoutputstreams.
2.12.2StreamsandFiles
Streamsfacilitateawaytocreatealevelofabstractionbetweentheprogramandan
input/outputdevice.Thisallowsacommonmethodofsendingandreceivingdata
amongstthevarioustypesofdevicesavailable.Therearetwotypesofstreams:text
andbinary.
Textstreamsarecomposedoflines.Eachlinehaszeroormorecharactersandare
terminatedbyanewlinecharacterwhichisthelastcharacterinaline.Conversions
mayoccurontextstreamsduringinputandoutput.Textstreamsconsistofonly
printablecharacters,thetabcharacter,andthenewlinecharacter.Spacescannot
appearbeforeanewlinecharacter,althoughitisimplementationdefinedwhether
ornotreadingatextstreamremovesthesespaces.Animplementationmustsupport
linesofuptoatleast254charactersincludingthenewlinecharacter.
Binarystreamsinputandoutputdatainanexactly1:1ratio.Noconversionexists
andallcharactersmaybetransferred.
Whenaprogrambegins,therearealreadythreeavailablestreams:standardinput,
standardoutput,andstandarderror.
Filesareassociatedwithstreamsandmustbeopenedtobeused.ThepointofI/O
withinafileisdeterminedbythefileposition.Whenafileisopened,thefileposition
pointstothebeginningofthefileunlessthefileisopenedforanappendoperation
inwhichcasethepositionpointstotheendofthefile.Thefilepositionfollowsread
andwriteoperationstoindicatewherethenextoperationwilloccur.
Whenafileisclosed,nomoreactionscanbetakenonituntilitisopenedagain.
Exitingfromthemainfunctioncausesallopenfilestobeclosed.
2.12.3FileFunctions
2.12.3.1clearerr
Declaration:
void clearerr(FILE *stream);
Clearstheendoffileanderrorindicatorsforthegivenstream.Aslongastheerror
indicatorisset,allstreamoperationswillreturnanerroruntilclearerrorrewindis
called.
2.12.3.2fclose
Declaration:
int fclose(FILE *stream);
Closesthestream.Allbuffersareflushed.
Ifsuccessful,itreturnszero.OnerroritreturnsEOF.
2.12.3.3feof
Declaration:
int feof(FILE *stream);
Teststheendoffileindicatorforthegivenstream.Ifthestreamisattheendof
file,thenitreturnsanonzerovalue.Ifitisnotattheendofthefile,thenit
returnszero.
2.12.3.4ferror
Declaration:
int ferror(FILE *stream);
Teststheerrorindicatorforthegivenstream.Iftheerrorindicatorisset,thenit
returnsanonzerovalue.Iftheerrorindicatorisnotset,thenitreturnszero.
2.12.3.5fflush
Declaration:
int fflush(FILE *stream);
Flushestheoutputbufferofastream.Ifstreamisanullpointer,thenalloutput
buffersareflushed.
Ifsuccessful,itreturnszero.OnerroritreturnsEOF.
2.12.3.6fgetpos
Declaration:
int fgetpos(FILE *stream, fpos_t *pos);
Getsthecurrentfilepositionofthestreamandwritesittopos.
Ifsuccessful,itreturnszero.Onerroritreturnsanonzerovalueandstorestheerrornumberin
thevariableerrno.
2.12.3.7fopen
Declaration:
FILE *fopen(const char *filename, const char *mode);
Opensthefilenamepointedtobyfilename.Themodeargumentmaybeoneofthefollowing
constantstrings:
r readtextmode
w writetextmode(truncatesfiletozerolengthorcreatesnewfile)
a appendtextmodeforwriting(opensorcreatesfileandsetsfile
pointertotheendoffile)
rb readbinarymode
wb writebinarymode(truncatesfiletozerolengthorcreatesnewfile)
ab appendbinarymodeforwriting(opensorcreatesfileandsetsfile
pointertotheendoffile)
r+ readandwritetextmode
w+ readandwritetextmode(truncatesfiletozerolengthorcreates
newfile)
a+ readandwritetextmode(opensorcreatesfileandsetsfilepointer
totheendoffile)
r+b or rb+ readandwritebinarymode
w+b or wb+ readandwritebinarymode(truncatesfiletozerolengthorcreates
newfile)
a+b or ab+ readandwritebinarymode(opensorcreatesfileandsetsfile
pointertotheendoffile)
Ifthefiledoesnotexistanditisopenedwithreadmode(r),thentheopenfails.
Ifthefileisopenedwithappendmode(a),thenallwriteoperationsoccurattheendofthefile
regardlessofthecurrentfileposition.
Ifthefileisopenedintheupdatemode(+),thenoutputcannotbedirectlyfollowedbyinput
andinputcannotbedirectlyfollowedbyoutputwithoutaninterveningfseek,fsetpos,rewind,
orfflush.
Onsuccessapointertothefilestreamisreturned.Onfailureanullpointerisreturned.
2.12.3.8fread
Declaration:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
Readsdatafromthegivenstreamintothearraypointedtobyptr.It
readsnmembnumberofelementsofsizesize.Thetotalnumberofbytesreadis
(size*nmemb).
Onsuccessthenumberofelementsreadisreturned.Onerrororendoffilethetotalnumber
ofelementssuccessfullyread(whichmaybezero)isreturned.
2.12.3.9freopen
Declaration:
FILE *freopen(const char *filename, const char *mode, FILE *stream);
Associatesanewfilenamewiththegivenopenstream.Theoldfileinstreamis
closed.Ifanerroroccurswhileclosingthefile,theerrorisignored.Themode
argumentisthesameasdescribedinthefopencommand.Normallyusedfor
reassociatingstdin,stdout,orstderr.
Onsuccessthepointertothestreamisreturned.Onerroranullpointerisreturned.
2.12.3.10fseek
Declaration:
int fseek(FILE *stream, long int offset, int whence);
Setsthefilepositionofthestreamtothegivenoffset.The
argumentoffsetsignifiesthenumberofbytestoseekfromthegivenwhence
position.Theargumentwhencecanbe:
SEEK_SET Seeksfromthebeginningofthefile.
SEEK_CUR Seeksfromthecurrentposition.
SEEK_END Seeksfromtheendofthefile.

Onatextstream,whenceshouldbeSEEK_SETandoffsetshouldbeeitherzerooravalue
returnedfromftell.
Theendoffileindicatorisreset.TheerrorindicatorisNOTreset.
Onsuccesszeroisreturned.Onerroranonzerovalueisreturned.
2.12.3.11fsetpos
Declaration:
int fsetpos(FILE *stream, const fpos_t *pos);
Setsthefilepositionofthegivenstreamtothegivenposition.The
argumentposisapositiongivenbythefunctionfgetpos.Theendoffileindicator
iscleared.
Onsuccesszeroisreturned.Onerroranonzerovalueisreturnedandthevariableerrnoisset.
2.12.3.12ftell
Declaration:
long int ftell(FILE *stream);
Returnsthecurrentfilepositionofthegivenstream.Ifitisabinarystream,then
thevalueisthenumberofbytesfromthebeginningofthefile.Ifitisatext
stream,thenthevalueisavalueuseablebythefseekfunctiontoreturnthefile
positiontothecurrentposition.
Onsuccessthecurrentfilepositionisreturned.Onerroravalueof-1Lisreturnedanderrnois
set.
2.12.3.13fwrite
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
Writesdatafromthearraypointedtobyptrtothegivenstream.It
writesnmembnumberofelementsofsizesize.Thetotalnumberofbyteswritten
is(size*nmemb).
Onsuccessthenumberofelementswritenisreturned.Onerrorthetotalnumberofelements
successfullywriten(whichmaybezero)isreturned.
2.12.3.14remove
Declaration:
int remove(const char *filename);
Deletesthegivenfilenamesothatitisnolongeraccessible(unlinksthefile).Ifthe
fileiscurrentlyopen,thentheresultisimplementationdefined.
Onsuccesszeroisreturned.Onfailureanonzerovalueisreturned.
2.12.3.15rename
Declaration:
int rename(const char *old_filename, const char *new_filename);
Causesthefilenamereferredtobyold_filenametobechangedtonew_filename.
Ifthefilenamepointedtobynew_filenameexists,theresultisimplementation
defined.
Onsuccesszeroisreturned.Onerroranonzerovalueisreturnedandthefileisstillaccessible
byitsoldfilename.
2.12.3.16rewind
Declaration:
void rewind(FILE *stream);
Setsthefilepositiontothebeginningofthefileofthegivenstream.Theerror
andendoffileindicatorsarereset.
2.12.3.17setbuf
Declaration:
void setbuf(FILE *stream, char *buffer);
Defineshowastreamshouldbebuffered.Thisshouldbecalledafterthestream
hasbeenopenedbutbeforeanyoperationhasbeendoneonthestream.Input
andoutputisfullybuffered.ThedefaultBUFSIZisthesizeofthebuffer.The
argumentbufferpointstoanarraytobeusedasthebuffer.Ifbufferisanull
pointer,thenthestreamisunbuffered.
2.12.3.18setvbuf
Declaration:
int setvbuf(FILE *stream, char *buffer, int mode, size_t size);
Defineshowastreamshouldbebuffered.Thisshouldbecalledafterthestream
hasbeenopenedbutbeforeanyoperationhasbeendoneonthestream.The
argumentmodedefineshowthestreamshouldbebufferedasfollows:
_IOFBF Inputandoutputisfullybuffered.Ifthebufferisempty,aninput

operationattemptstofillthebuffer.Onoutputthebufferwillbe
completelyfilledbeforeanyinformationiswrittentothefile(orthe
streamisclosed).
_IOLBF Inputandoutputislinebuffered.Ifthebufferisempty,aninput

operationattemptstofillthebuffer.Onoutputthebufferwillbeflushed
wheneveranewlinecharacteriswritten.
_IONBF Inputandoutputisnotbuffered.Nobufferingisperformed.

Theargumentbufferpointstoanarraytobeusedasthebuffer.Ifbufferisanullpointer,
thensetvbufusesmalloctocreateitsownbuffer.
Theargumentsizedeterminesthesizeofthearray.
Onsuccesszeroisreturned.Onerroranonzerovalueisreturned.
2.12.3.19tmpfile
Declaration:
FILE *tmpfile(void);
Createsatemporaryfileinbinaryupdatemode(wb+).Thetempfileisremoved
whentheprogramterminatesorthestreamisclosed.
Onsuccessapointertoafilestreamisreturned.Onerroranullpointerisreturned.
2.12.3.20tmpnam
Declaration:
char *tmpnam(char *str);
Generatesandreturnsavalidtemporaryfilenamewhichdoesnotexist.Up
toTMP_MAXdifferentfilenamescanbegenerated.
Iftheargumentstrisanullpointer,thenthefunctionreturnsapointertoavalidfilename.If
theargumentstrisavalidpointertoanarray,thenthefilenameiswrittentothearrayanda
pointertothesamearrayisreturned.ThefilenamemaybeuptoL_tmpnamcharacterslong.
2.12.4FormattedI/OFunctions
2.12.4.1..printfFunctions
Declarations:
int fprintf(FILE *stream, const char *format, ...);
int printf(const char *format, ...);
int sprintf(char *str, const char *format, ...);
int vfprintf(FILE *stream, const char *format, va_list arg);
int vprintf(const char *format, va_list arg);
int vsprintf(char *str, const char *format, va_list arg);
The..printffunctionsprovideameanstooutputformattedinformationtoastream.
fprintf sendsformattedoutputtoastream
printf sendsformattedoutputtostdout
sprintf sendsformattedoutputtoastring
vfprintf sendsformattedoutputtoastreamusinganargumentlist
vprintf sendsformattedoutputtostdoutusinganargumentlist
vsprintf sendsformattedoutputtoastringusinganargumentlist

Thesefunctionstaketheformatstringspecifiedbytheformatargumentandapplyeach
followingargumenttotheformatspecifiersinthestringinalefttorightfashion.Each
characterintheformatstringiscopiedtothestreamexceptforconversioncharacterswhich
specifyaformatspecifier.
Thestringcommands(sprintfandvsprintf)appendanullcharactertotheendofthestring.
Thisnullcharacterisnotcountedinthecharactercount.
Theargumentlistcommands(vfprintf,vprintf,andvsprintf)useanargumentlistwhichis
preparedbyva_start.Thesecommandsdonotcallva_end (thecallermustcallit).
Aconversionspecifierbeginswiththe%character.Afterthe%charactercomethefollowingin
thisorder:
[flags] Controltheconversion(optional).
[width] Definesthenumberofcharacterstoprint(optional).
[.precision] Definestheamountofprecisiontoprintforanumbertype
(optional).
[modifier] Overridesthesize(type)oftheargument(optional).
[type] Thetypeofconversiontobeapplied(required).
Flags:
- Valueisleftjustified(defaultisrightjustified).Overridesthe0flag.
+ Forcesthesign(+or)toalwaysbeshown.Defaultistojustshowthe
sign.Overridesthespaceflag.
space Causesapositivevaluetodisplayaspaceforthesign.Negativevaluesstill
showthesign.
# Alternateform:
ConversionCharacter Result
o Precisionisincreasedtomakethefirstdigitazero.
X or x Nonzerovaluewillhave0xor0Xprefixedtoit.
E, e, f, g, or G Resultwillalwayshaveadecimalpoint.
G or g

Trailingzeroswillnotberemoved.
0 Ford,i,o,u,x,X,e,E,f,g,andGleadingzerosareusedtopadthefield
widthinsteadofspaces.Thisisusefulonlywithawidthspecifier.Precision
overridesthisflag.
Width:
Thewidthofthefieldisspecifiedherewithadecimalvalue.Ifthevalueisnotlargeenoughto
fillthewidth,thentherestofthefieldispaddedwithspaces(unlessthe0flagisspecified).If
thevalueoverflowsthewidthofthefield,thenthefieldisexpandedtofitthevalue.Ifa*is
usedinplaceofthewidthspecifer,thenthenextargument(whichmustbeaninttype)
specifiesthewidthofthefield.Note:whenusingthe*withthewidthand/orprecision
specifier,thewidthargumentcomesfirst,thentheprecisionargument,thenthevaluetobe
converted.
Precision:
Theprecisionbeginswithadot(.)todistinguishitselffromthewidthspecifier.Theprecision
canbegivenasadecimalvalueorasanasterisk(*).Ifa*isused,thenthenextargument
(whichisaninttype)specifiestheprecision.Note:whenusingthe*withthewidthand/or
precisionspecifier,thewidthargumentcomesfirst,thentheprecisionargument,thenthe
valuetobeconverted.Precisiondoesnotaffectthectype.
[.precision] Result
(none) Defaultprecisionvalues:
1ford,i,o,u,x,Xtypes.Theminimumnumberofdigitstoappear.
6forf,e,Etypes.Specifiesthenumberofdigitsafterthedecimal
point.
ForgorGtypesallsignificantdigitsareshown.
Forstypeallcharactersinstringareprintuptobutnotincludingthe
nullcharacter.
.or.0 Ford,i,o,u,x,Xtypesthedefaultprecisionvalueisusedunlessthe
valueiszeroinwhichcasenocharactersareprinted.
Forf,e,Etypesnodecimalpointcharacterordigitsareprinted.
ForgorGtypestheprecisionisassumedtobe1.
.n Ford,i,o,u,x,Xtypesthenatleastndigitsareprinted(paddingwith
zerosifnecessary).
Forf,e,Etypesspecifiesthenumberofdigitsafterthedecimalpoint.
ForgorGtypesspecifiesthenumberofsignificantdigitstoprint.
Forstypespecifiesthemaximumnumberofcharacterstoprint.

Modifier:
Amodifierchangesthewayaconversionspecifiertypeisinterpreted.

[modifier] [type] Effect


h d,i,o,u, x,X Value is first converted to a short int or unsigned
short i nt.
h n Specifies that the pointer points to a short int.
l d,i,o,u, x,X Value is first converted to a long int or unsigned
long int .
l n Specifies that the pointer points to a long int.
L e,E,f,g,G Value is first converted to a long double.

Conversionspecifiertype:
Theconversionspecifierspecifieswhattypetheargumentistobetreatedas.
[type] Output
d,i Typesigned int.
o Typeunsigned intprintedinoctal.
u Typeunsigned intprintedindecimal.
x Typeunsigned intprintedinhexadecimalasddddusinga,b,c,d,e,f.
X Typeunsigned intprintedinhexadecimalasddddusingA,B,C,D,E,F.
f Typedoubleprintedas[]ddd.ddd.
e,E Typedoubleprintedas[]d.dddeddwherethereisonedigitprinted
beforethedecimal(zeroonlyifthevalueiszero).Theexponentcontains
atleasttwodigits.IftypeisEthentheexponentisprintedwithacapital
E.
g,G TypedoubleprintedastypeeorEiftheexponentislessthan4orgreater
thanorequaltotheprecision.Otherwiseprintedastypef.Trailingzeros
areremoved.Decimalpointcharacterappearsonlyifthereisanonzero
decimaldigit.
c Typechar.Singlecharacterisprinted.
s Typepointertoarray.Stringisprintedaccordingtoprecision(no
precisionprintsentirestring).
p Printsthevalueofapointer(thememorylocationitholds).
n Theargumentmustbeapointertoan int.Storesthenumberof
charactersprintedthusfarintheint.Nocharactersareprinted.
% A%signisprinted.
Thenumberofcharactersprintedarereturned.Ifanerroroccurred,1isreturned.

2.12.4.2..scanfFunctions
Declarations:
int fscanf(FILE *stream, const char *format, ...);
int scanf(const char *format, ...);
int sscanf(const char *str, const char *format, ...);
The..scanffunctionsprovideameanstoinputformattedinformationfromastream.
fscanf readsformattedinputfromastream
scanf readsformattedinputfromstdin
sscanf readsformattedinputfromastring
Thesefunctionstakeinputinamannerthatisspecifiedbytheformatargumentandstoreeach
inputfieldintothefollowingargumentsinalefttorightfashion.
Eachinputfieldisspecifiedintheformatstringwithaconversionspecifierwhichspecifieshow
theinputistobestoredintheappropriatevariable.Othercharactersintheformatstring
specifycharactersthatmustbematchedfromtheinput,butarenotstoredinanyofthe
followingarguments.Iftheinputdoesnotmatchthenthefunctionstopsscanningandreturns.
Awhitespacecharactermaymatchwithanywhitespacecharacter(space,tab,carriagereturn,
newline,verticaltab,orformfeed)orthenextincompatiblecharacter.
Aninputfieldisspecifiedwithaconversionspeciferwhichbeginswiththe%character.After
the%charactercomethefollowinginthisorder:
[*] Assignmentsuppressor(optional).
[width] Definesthemaximumnumberofcharacterstoread(optional).
[modifier] Overridesthesize(type)oftheargument(optional).
[type] Thetypeofconversiontobeapplied(required).
Assignmentsuppressor:
Causestheinputfieldtobescannedbutnotstoredinavariable.
Width:
Themaximumwidthofthefieldisspecifiedherewithadecimalvalue.Iftheinputissmaller
thanthewidthspecifier(i.e.itreachesanonconvertiblecharacter),thenwhatwasreadthusfar
isconvertedandstoredinthevariable.
Modifier:
Amodifierchangesthewayaconversionspecifiertypeisinterpreted.
[modifier] [type] Effect
h d,i,o,u, x Theargumentisa short int or unsigned short int.</td>
h n Specifiesthatthepointerpointstoa short int.
l d,i,o,u, x Theargumentisa long int or unsigned long int.
l n Specifiesthatthepointerpointstoa long int.
l e,f,g Theargumentisa double.
L e,f,g Theargumentisa long double.

Conversionspecifiertype:
Theconversionspecifierspecifieswhattypetheargumentis.Italsocontrolswhatavalid
convertiblecharacteris(whatkindofcharactersitcanreadsoitcanconverttosomething
compatible).
[type] Input
d Typesigned intrepresentedinbase10.Digits0through9andthesign
(+or).
i Typesigned int.Thebase(radix)isdependentonthefirsttwo
characters.Ifthefirstcharacterisadigitfrom1to9,thenitisbase10.
Ifthefirstdigitisazeroandtheseconddigitisadigitfrom1to7,then
itisbase8(octal).Ifthefirstdigitisazeroandthesecondcharacteris
anxorX,thenitisbase16(hexadecimal).
o Typeunsigned int.Theinputmustbeinbase8(octal).Digits0through
7only.
u Typeunsigned int.Theinputmustbeinbase10(decimal).Digits0
through9only.
x,X Typeunsigned int.Theinputmustbeinbase16(hexadecimal).Digits0
through9orAthroughZorathroughz.Thecharacters0xor0Xmaybe
optionallyprefixedtothevalue.
e,E,f,g,G Typefloat.Beginswithanoptionalsign.Thenoneormoredigits,
followedbyanoptionaldecimalpointanddecimalvalue.Finallyended
withanoptionalsignedexponentvaluedesignatedwithaneorE.
s Typecharacterarray.Inputsasequenceofnonwhitespacecharacters
(space,tab,carriagereturn,newline,verticaltab,orformfeed).The
arraymustbelargeenoughtoholdthesequenceplusanullcharacter
appendedtotheend.
[...] Typecharacterarray.Allowsasearchsetofcharacters.Allowsinputof
onlythosecharacterencapsulatedinthebrackets(thescanset).Ifthe
firstcharacterisacarrot(^),thenthescansetisinvertedandallowsany
ASCIIcharacterexceptthosespecifiedbetweenthebrackets.Onsome
systemsarangecanbespecifiedwiththedashcharacter().By
specifyingthebeginningcharacter,adash,andanendingcharactera
rangeofcharacterscanbeincludedinthescanset.Anullcharacteris
appendedtotheendofthearray.
c Typecharacterarray.Inputsthenumberofcharactersspecifiedinthe
widthfield.Ifnowidthfieldisspecified,then1isassumed.Nonull
characterisappendedtothearray.
p Pointertoapointer.Inputsamemoryaddressinthesamefashionof
the%ptypeproducedbytheprintffunction.
n Theargumentmustbeapointertoan int.Storesthenumberof
charactersreadthusfarintheint.Nocharactersarereadfromthe
inputstream.
% Requiresamatching% signfromtheinput.
Readinganinputfield(designatedwithaconversionspecifier)endswhenanincompatible
characterismet,orthewidthfieldissatisfied.
Onsuccessthenumberofinputfieldsconvertedandstoredarereturned.Ifaninputfailure
occurred,thenEOFisreturned.
2.12.5CharacterI/OFunctions
2.12.5.1fgetc
Declaration:
int fgetc(FILE *stream);
Getsthenextcharacter(anunsigned char)fromthespecifiedstreamand
advancesthepositionindicatorforthestream.
Onsuccessthecharacterisreturned.Iftheendoffileisencountered,thenEOFisreturnedand
theendoffileindicatorisset.Ifanerroroccursthentheerrorindicatorforthestreamisset
andEOFisreturned.
2.12.5.2fgets
Declaration:
char *fgets(char *str, int n, FILE *stream);
Readsalinefromthespecifiedstreamandstoresitintothestringpointedto
bystr.Itstopswheneither(n1)charactersareread,thenewlinecharacteris
read,ortheendoffileisreached,whichevercomesfirst.Thenewlinecharacteris
copiedtothestring.Anullcharacterisappendedtotheendofthestring.
Onsuccessapointertothestringisreturned.Onerroranullpointerisreturned.Iftheendof
fileoccursbeforeanycharactershavebeenread,thestringremainsunchanged.
2.12.5.3fputc
Declaration:
int fputc(int char, FILE *stream);
Writesacharacter(anunsigned char)specifiedbytheargumentchartothe
specifiedstreamandadvancesthepositionindicatorforthestream.
Onsuccessthecharacterisreturned.Ifanerroroccurs,theerrorindicatorforthestreamisset
andEOFisreturned.
2.12.5.4fputs
Declaration:
int fputs(const char *str, FILE *stream);
Writesastringtothespecifiedstreamuptobutnotincludingthenullcharacter.
Onsuccessanonnegativevalueisreturned.OnerrorEOFisreturned.
2.12.5.5getc
Declaration:
int getc(FILE *stream);
Getsthenextcharacter(anunsigned char)fromthespecifiedstreamand
advancesthepositionindicatorforthestream.
Thismaybeamacroversionoffgetc.
Onsuccessthecharacterisreturned.Iftheendoffileisencountered,thenEOFisreturnedand
theendoffileindicatorisset.Ifanerroroccursthentheerrorindicatorforthestreamisset
andEOFisreturned.
2.12.5.6getchar
Declaration:
int getchar(void);
Getsacharacter(anunsigned char)fromstdin.
Onsuccessthecharacterisreturned.Iftheendoffileisencountered,thenEOFisreturnedand
theendoffileindicatorisset.Ifanerroroccursthentheerrorindicatorforthestreamisset
andEOFisreturned.
2.12.5.7gets
Declaration:
char *gets(char *str);
Readsalinefromstdinandstoresitintothestringpointedtobystr.Itstops
wheneitherthenewlinecharacterisreadorwhentheendoffileisreached,
whichevercomesfirst.Thenewlinecharacterisnotcopiedtothestring.Anull
characterisappendedtotheendofthestring.
Onsuccessapointertothestringisreturned.Onerroranullpointerisreturned.Iftheendof
fileoccursbeforeanycharactershavebeenread,thestringremainsunchanged.
2.12.5.8putc
Declaration:
int putc(int char, FILE *stream);
Writesacharacter(anunsigned char)specifiedbytheargumentchartothe
specifiedstreamandadvancesthepositionindicatorforthestream.
Thismaybeamacroversionoffputc.
Onsuccessthecharacterisreturned.Ifanerroroccurs,theerrorindicatorforthestreamisset
andEOFisreturned.
2.12.5.9putchar
Declaration:
int putchar(int char);
Writesacharacter(anunsigned char)specifiedbytheargumentchartostdout.
Onsuccessthecharacterisreturned.Ifanerroroccurs,theerrorindicatorforthestreamisset
andEOFisreturned.
2.12.5.10puts
Declaration:
int puts(const char *str);
Writesastringtostdoutuptobutnotincludingthenullcharacter.Anewline
characterisappendedtotheoutput.
Onsuccessanonnegativevalueisreturned.OnerrorEOFisreturned.
2.12.5.11ungetc
Declaration:
int ungetc(int char, FILE *stream);
Pushesthecharacterchar(anunsigned char)ontothespecifiedstreamsothat
thethisisthenextcharacterread.Thefunctionsfseek,fsetpos,
andrewinddiscardanycharacterspushedontothestream.
MultiplecharacterspushedontothestreamarereadinaFIFOmanner(firstin,firstout).
Onsuccessthecharacterpushedisreturned.OnerrorEOFisreturned.
2.12.7ErrorFunctions
2.12.7.1perror
Declaration:
void perror(const char *str);
Printsadescriptiveerrormessagetostderr.Firstthestringstrisprintedfollowed
byacolonthenaspace.Thenanerrormessagebasedonthecurrentsettingof
thevariableerrnoisprinted.

2.13stdlib.h

Thestdlibheaderdefinesseveralgeneraloperationfunctionsandmacros.
Macros:
NULL
EXIT_FAILURE
EXIT_SUCCESS
RAND_MAX
MB_CUR_MAX
Variables:
typedef size_t
typedef wchar_t
struct div_t
struct ldiv_t
Functions:
abort();
abs();
atexit();
atof();
atoi();
atol();
bsearch();
calloc();
div();
exit();
free();
getenv();
labs();
ldiv();
malloc();
mblen();
mbstowcs();
mbtowc();
qsort();
rand();
realloc();
srand();
strtod();
strtol();
strtoul();
system();
wcstombs();
wctomb();
2.13.1VariablesandDefinitions
size_tistheunsignedintegerresultofthesizeofkeyword.
wchar_tisanintegertypeofthesizeofawidecharacterconstant.
div_tisthestructurereturnedbythedivfunction.
ldiv_tisthestructurereturnedbytheldivfunction.
NULListhevalueofanullpointerconstant.
EXIT_FAILUREandEXIT_SUCCESSarevaluesfortheexitfunctiontoreturntermination
status.
RAND_MAXisthemaximumvaluereturnedbytherandfunction.
MB_CUR_MAXisthemaximumnumberofbytesinamultibytecharactersetwhich
cannotbelargerthanMB_LEN_MAX.
2.13.2StringFunctions
2.13.2.1atof
Declaration:
double atof(const char *str);
Thestringpointedtobytheargumentstrisconvertedtoafloatingpointnumber
(typedouble).Anyinitialwhitespacecharactersareskipped(space,tab,carriage
return,newline,verticaltab,orformfeed).Thenumbermayconsistofanoptional
sign,astringofdigitswithanoptionaldecimalcharacter,andan
optionaleorEfollowedbyaoptionallysignedexponent.Conversionstopswhenthe
firstunrecognizedcharacterisreached.
Onsuccesstheconvertednumberisreturned.Ifnoconversioncanbemade,zerois
returned.Ifthevalueisoutofrangeofthetypedouble,thenHUGE_VALisreturned
withtheappropriatesignandERANGEisstoredinthevariableerrno.Ifthevalueistoo
smalltobereturnedinthetypedouble,thenzeroisreturnedandERANGEisstoredin
thevariableerrno.
2.13.2.2atoi
Declaration:
int atoi(const char *str);
Thestringpointedtobytheargumentstrisconvertedtoaninteger(typeint).Any
initialwhitespacecharactersareskipped(space,tab,carriagereturn,newline,
verticaltab,orformfeed).Thenumbermayconsistofanoptionalsignandastringof
digits.Conversionstopswhenthefirstunrecognizedcharacterisreached.
Onsuccesstheconvertednumberisreturned.Ifthenumbercannotbeconverted,
then0isreturned.
2.13.2.3atol
Declaration:
long int atol(const char *str);
Thestringpointedtobytheargumentstrisconvertedtoalonginteger(typelong
int).Anyinitialwhitespacecharactersareskipped(space,tab,carriagereturn,new
line,verticaltab,orformfeed).Thenumbermayconsistofanoptionalsignanda
stringofdigits.Conversionstopswhenthefirstunrecognizedcharacterisreached.
Onsuccesstheconvertednumberisreturned.Ifthenumbercannotbeconverted,
then0isreturned.
2.13.2.4strtod
Declaration:
double strtod(const char *str, char **endptr);
Thestringpointedtobytheargumentstrisconvertedtoafloatingpointnumber
(typedouble).Anyinitialwhitespacecharactersareskipped(space,tab,carriage
return,newline,verticaltab,orformfeed).Thenumbermayconsistofanoptional
sign,astringofdigitswithanoptionaldecimalcharacter,andan
optionaleorEfollowedbyaoptionallysignedexponent.Conversionstopswhenthe
firstunrecognizedcharacterisreached.
Theargumentendptrisapointertoapointer.Theaddressofthecharacterthat
stoppedthescanisstoredinthepointerthatendptrpointsto.
Onsuccesstheconvertednumberisreturned.Ifnoconversioncanbemade,zerois
returned.Ifthevalueisoutofrangeofthetypedouble,thenHUGE_VALisreturned
withtheappropriatesignandERANGEisstoredinthevariableerrno.Ifthevalueistoo
smalltobereturnedinthetypedouble,thenzeroisreturnedandERANGEisstoredin
thevariableerrno.
2.13.2.5strtol
Declaration:
long int strtol(const char *str, char **endptr, int base);
Thestringpointedtobytheargumentstrisconvertedtoalonginteger(typelong
int).Anyinitialwhitespacecharactersareskipped(space,tab,carriagereturn,new
line,verticaltab,orformfeed).Thenumbermayconsistofanoptionalsignanda
stringofdigits.Conversionstopswhenthefirstunrecognizedcharacterisreached.
Ifthebase(radix)argumentiszero,thentheconversionisdependentonthefirst
twocharacters.Ifthefirstcharacterisadigitfrom1to9,thenitisbase10.Ifthe
firstdigitisazeroandtheseconddigitisadigitfrom1to7,thenitisbase8(octal).
IfthefirstdigitisazeroandthesecondcharacterisanxorX,thenitisbase16
(hexadecimal).
Ifthebaseargumentisfrom2to36,thenthatbase(radix)isusedandany
charactersthatfalloutsideofthatbasedefinitionareconsideredunconvertible.For
base11to36,thecharactersAtoZ(oratoz)areused.Ifthebaseis16,thenthe
characters0xor0Xmayprecedethenumber.
Theargumentendptrisapointertoapointer.Theaddressofthecharacterthat
stoppedthescanisstoredinthepointerthatendptrpointsto.
Onsuccesstheconvertednumberisreturned.Ifnoconversioncanbemade,zerois
returned.Ifthevalueisoutoftherangeofthetypelong int,
thenLONG_MAXorLONG_MINisreturnedwiththesignofthecorrectvalueandERANGEis
storedinthevariableerrno.
2.13.2.6strtoul
Declaration:
unsigned long int strtoul(const char *str, char **endptr, int base);
Thestringpointedtobytheargumentstrisconvertedtoanunsignedlonginteger
(typeunsigned long int).Anyinitialwhitespacecharactersareskipped(space,tab,
carriagereturn,newline,verticaltab,orformfeed).Thenumbermayconsistofan
optionalsignandastringofdigits.Conversionstopswhenthefirstunrecognized
characterisreached.
Ifthebase(radix)argumentiszero,thentheconversionisdependentonthefirst
twocharacters.Ifthefirstcharacterisadigitfrom1to9,thenitisbase10.Ifthe
firstdigitisazeroandtheseconddigitisadigitfrom1to7,thenitisbase8(octal).
IfthefirstdigitisazeroandthesecondcharacterisanxorX,thenitisbase16
(hexadecimal).
Ifthebaseargumentisfrom2to36,thenthatbase(radix)isusedandany
charactersthatfalloutsideofthatbasedefinitionareconsideredunconvertible.For
base11to36,thecharactersAtoZ(oratoz)areused.Ifthebaseis16,thenthe
characters0xor0Xmayprecedethenumber.
Theargumentendptrisapointertoapointer.Theaddressofthecharacterthat
stoppedthescanisstoredinthepointerthatendptrpointsto.
Onsuccesstheconvertednumberisreturned.Ifnoconversioncanbemade,zerois
returned.Ifthevalueisoutoftherangeofthetypeunsigned long int,
thenULONG_MAXisreturnedandERANGEisstoredinthevariableerrno.
2.13.3MemoryFunctions
2.13.3.1calloc
Declaration:
void *calloc(size_t nitems, size_t size);
Allocatestherequestedmemoryandreturnsapointertoit.Therequestedsize
isnitemseachsizebyteslong(totalmemoryrequestedisnitems*size).Thespaceis
initializedtoallzerobits.
Onsuccessapointertotherequestedspaceisreturned.Onfailureanullpointeris
returned.
2.13.3.2free
Declaration:
void free(void *ptr);
Deallocatesthememorypreviouslyallocatedbyacalltocalloc,malloc,orrealloc.
Theargumentptrpointstothespacethatwaspreviouslyallocated.Ifptrpointstoa
memoryblockthatwasnotallocatedwithcalloc,malloc,orrealloc,orisaspace
thathasbeendeallocated,thentheresultisundefined.
Novalueisreturned.
2.13.3.3malloc
Declaration:
void *malloc(size_t size);
Allocatestherequestedmemoryandreturnsapointertoit.Therequestedsize
issizebytes.Thevalueofthespaceisindeterminate.
Onsuccessapointertotherequestedspaceisreturned.Onfailureanullpointeris
returned.
2.13.3.4realloc
Declaration:
void *realloc(void *ptr, size_t size);
Attemptstoresizethememoryblockpointedtobyptrthatwaspreviouslyallocated
withacalltomallocorcalloc.Thecontentspointedtobyptrareunchanged.Ifthe
valueofsizeisgreaterthantheprevioussizeoftheblock,thentheadditionalbytes
haveanundeterminatevalue.Ifthevalueofsizeislessthantheprevioussizeofthe
block,thenthedifferenceofbytesattheendoftheblockarefreed.Ifptrisnull,
thenitbehaveslikemalloc.Ifptrpointstoamemoryblockthatwasnotallocated
withcallocormalloc,orisaspacethathasbeendeallocated,thentheresultis
undefined.Ifthenewspacecannotbeallocated,thenthecontentspointedto
byptrareunchanged.Ifsizeiszero,thenthememoryblockiscompletelyfreed.
Onsuccessapointertothememoryblockisreturned(whichmaybeinadifferent
locationasbefore).Onfailureorifsizeiszero,anullpointerisreturned.
2.13.4EnvironmentFunctions
2.13.4.1abort
Declaration:
void abort(void);
Causesanabnormalprogramtermination.RaisestheSIGABRTsignalandan
unsuccessfulterminationstatusisreturnedtotheenvironment.Whetherornot
openstreamsareclosedisimplementationdefined.
Noreturnispossible.
2.13.4.2atexit
Declaration:
int atexit(void (*func)(void));
Causesthespecifiedfunctiontobecalledwhentheprogramterminatesnormally.At
least32functionscanberegisteredtobecalledwhentheprogramterminates.They
arecalledinalastin,firstoutbasis(thelastfunctionregisterediscalledfirst).
Onsuccesszeroisreturned.Onfailureanonzerovalueisreturned.
2.13.4.3exit
Declaration:
void exit(int status);
Causestheprogramtoterminatenormally.Firstthefunctionsregisteredbyatexit
arecalled,thenallopenstreamsareflushedandclosed,andalltemporaryfiles
openedwithtmpfileareremoved.Thevalueofstatusisreturnedtothe
environment.IfstatusisEXIT_SUCCESS,thenthissignifiesasuccessfultermination.
IfstatusisEXIT_FAILURE,thenthissignifiesanunsuccessfultermination.Allother
valuesareimplementationdefined.
Noreturnispossible.
2.13.4.4getenv
Declaration:
char *getenv(const char *name);
Searchesfortheenvironmentstringpointedtobynameandreturnstheassociated
valuetothestring.Thisreturnedvalueshouldnotbewrittento.
Ifthestringisfound,thenapointertothestring'sassociatedvalueisreturned.Ifthe
stringisnotfound,thenanullpointerisreturned.
2.13.4.5system
Declaration:
int system(const char *string);
Thecommandspecifiedbystringispassedtothehostenvironmenttobeexecuted
bythecommandprocessor.Anullpointercanbeusedtoinquirewhetherornotthe
commandprocessorexists.
Ifstringisanullpointerandthecommandprocessorexists,thenzeroisreturned.All
otherreturnvaluesareimplementationdefined.
2.13.5SearchingandSortingFunctions
2.13.5.1bsearch
Declaration:
void *bsearch(const void *key, const void *base, size_t nitems, size_t size,
int (*compar)(const void *, const void *));
Performsabinarysearch.Thebeginningofthearrayispointedtobybase.It
searchesforanelementequaltothatpointedtobykey.Thearrayisnitemslong
witheachelementinthearraysizebyteslong.
Themethodofcomparingisspecifiedbythecomparfunction.Thisfunctiontakes
twoarguments,thefirstisthekeypointerandthesecondisthecurrentelementin
thearraybeingcompared.Thisfunctionmustreturnlessthanzeroifthecompared
valueislessthanthespecifiedkey.Itmustreturnzeroifthecomparedvalueisequal
tothespecifiedkey.Itmustreturngreaterthanzeroifthecomparedvalueisgreater
thanthespecifiedkey.
Thearraymustbearrangedsothatelementsthatcomparelessthankeyarefirst,
elementsthatequalkeyarenext,andelementsthataregreaterthankeyarelast.
Ifamatchisfound,apointertothismatchisreturned.Otherwiseanullpointeris
returned.Ifmultiplematchingkeysarefound,whichkeyisreturnedisunspecified.
2.13.5.2qsort
Declaration:
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void
*, const void*));
Sortsanarray.Thebeginningofthearrayispointedtobybase.Thearray
isnitemslongwitheachelementinthearraysizebyteslong.
Theelementsaresortedinascendingorderaccordingtothecomparfunction.This
functiontakestwoarguments.Theseargumentsaretwoelementsbeingcompared.
Thisfunctionmustreturnlessthanzeroifthefirstargumentislessthanthesecond.
Itmustreturnzeroifthefirstargumentisequaltothesecond.Itmustreturngreater
thanzeroifthefirstargumentisgreaterthanthesecond.
Ifmultipleelementsareequal,theordertheyaresortedinthearrayisunspecified.
Novalueisreturned.
Example:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
char string_array[10][50]={"John",
"Jane",
"Mary",
"Rogery",
"Dave",
"Paul",
"Beavis",
"Astro",
"George",
"Elroy"};

/* Sort the list */


qsort(string_array,10,50,strcmp);

/* Search for the item "Elroy" and print it */


printf("%s",bsearch("Elroy",string_array,10,50,strcmp));

return 0;
}
2.13.6MathFunctions
2.13.6.1abs
Declaration:
int abs(int x);
Returnstheabsolutevalueofx.Notethatintwo'scomplimentthatthemost
maximumnumbercannotberepresentedasapositivenumber.Theresultinthis
caseisundefined.
Theabsolutevalueisreturned.
2.13.6.2div
Declaration:
div_t div(int numer, int denom);
Dividesnumer(numerator)bydenom(denominator).Theresultisstoredinthe
structurediv_twhichhastwomembers:
int qout;
int rem;
Wherequotisthequotientandremistheremainder.Inthecaseofinexact
division,quotisroundeddowntothenearestinteger.Thevaluenumerisequal
toquot * denom + rem.
Thevalueofthedivisionisreturnedinthestructure.
2.13.6.3labs
Declaration:
long int labs(long int x);
Returnstheabsolutevalueofx.Notthatintwo'scomplimentthatthemost
maximumnumbercannotberepresentedasapositivenumber.Theresultinthis
caseisundefined.
Theabsolutevalueisreturned.
2.13.6.4ldiv
Declaration:
ldiv_t ldiv(long int numer, long int denom);
Dividesnumer(numerator)bydenom(denominator).Theresultisstoredinthe
structureldiv_twhichhastwomembers:
long int qout;
long int rem;
Wherequotisthequotientandremistheremainder.Inthecaseofinexact
division,quotisroundeddowntothenearestinteger.Thevaluenumerisequal
toquot * denom + rem.
Thevalueofthedivisionisreturnedinthestructure.
2.13.6.5rand
Declaration:
int rand(void);
Returnsapseudorandomnumberintherangeof0toRAND_MAX.
Therandomnumberisreturned.
2.13.6.6srand
Declaration:
void srand(unsigned int seed);
Thisfunctionseedstherandomnumbergeneratorusedbythefunctionrand.
Seedingsrandwiththesameseedwillcauserandtoreturnthesamesequenceof
pseudorandomnumbers.Ifsrandisnotcalled,randactsasifsrand(1)hasbeen
called.
Novalueisreturned.
2.13.7MultibyteFunctions
ThebehaviorofthemultibytefunctionsareaffectedbythesettingofLC_CTYPEinthe
locationsettings.
2.13.7.1mblen
Declaration:
int mblen(const char *str, size_t n);
Returnsthelengthofamultibytecharacterpointedtobytheargumentstr.At
mostnbyteswillbeexamined.
Ifstrisanullpointer,thenzeroisreturnedifmultibytecharactersarenotstate
dependent(shiftstate).Otherwiseanonzerovalueisreturnedifmultibytecharacter
arestatedependent.
Ifstrisnotnull,thenthenumberofbytesthatarecontainedinthemultibyte
characterpointedtobystrarereturned.Zeroisreturnedifstrpointstoanull
character.Avalueof1isreturnedifstrdoesnotpointtoavalidmultibyte
character.
2.13.7.2mbstowcs
Declaration:
size_t mbstowcs(schar_t *pwcs, const char *str, size_t n);
Convertsthestringofmultibytecharacterspointedtobytheargumentstrtothe
arraypointedtobypwcs.Itstoresnomorethannvaluesintothearray.Conversion
stopswhenitreachesthenullcharacterornvalueshavebeenstored.Thenull
characterisstoredinthearrayaszerobutisnotcountedinthereturnvalue.
Ifaninvalidmultibytecharacterisreached,thenthevalue1isreturned.Otherwise
thenumberofvaluesstoredinthearrayisreturnednotincludingtheterminating
zerocharacter.
2.13.7.3mbtowc
Declaration:
int mbtowc(whcar_t *pwc, const char *str, size_t n);
Examinesthemultibytecharacterpointedtobytheargumentstr.Thevalueis
convertedandstoredintheargumentpwcifpwcisnotnull.Itscansatmostnbytes.
Ifstrisanullpointer,thenzeroisreturnedifmultibytecharactersarenotstate
dependent(shiftstate).Otherwiseanonzerovalueisreturnedifmultibytecharacter
arestatedependent.
Ifstrisnotnull,thenthenumberofbytesthatarecontainedinthemultibyte
characterpointedtobystrarereturned.Zeroisreturnedifstrpointstoanull
character.Avalueof1isreturnedifstrdoesnotpointtoavalidmultibyte
character.
2.13.7.4wcstombs
Declaration:
size_t wcstombs(char *str, const wchar_t *pwcs, size_t n);
Convertsthecodesstoredinthearraypwcstomultibytecharactersandstoresthem
inthestringstr.Itcopiesatmostnbytestothestring.Ifamultibytecharacter
overflowsthenconstriction,thennoneofthatmultibytecharacter'sbytesare
copied.Conversionstopswhenitreachesthenullcharacterornbyteshavebeen
writtentothestring.Thenullcharacterisstoredinthestring,butisnotcountedin
thereturnvalue.
Ifaninvalidcodeisreached,thevalue1isreturned.Otherwisethenumberofbytes
storedinthestringisreturnednotincludingtheterminatingnullcharacter.
2.13.7.5wctomb
Declaration:
int wctomb(char *str, wchar_t wchar);
Examinesthecodewhichcorrespondstoamultibytecharactergivenbythe
argumentwchar.Thecodeisconvertedtoamultibytecharacterandstoredintothe
stringpointedtobytheargumentstrifstrisnotnull.
Ifstrisanullpointer,thenzeroisreturnedifmultibytecharactersarenotstate
dependent(shiftstate).Otherwiseanonzerovalueisreturnedifmultibytecharacter
arestatedependent.
Ifstrisnotnull,thenthenumberofbytesthatarecontainedinthemultibyte
characterwchararereturned.Avalueof1isreturnedifwcharisnotavalid
multibytecharacter.

2.14string.h

Thestringheaderprovidesmanyfunctionsusefulformanipulatingstrings(character
arrays).
Macros:
NULL
Variables:
typedef size_t
Functions:
memchr();
memcmp();
memcpy();
memmove();
memset();
strcat();
strncat();
strchr();
strcmp();
strncmp();
strcoll();
strcpy();
strncpy();
strcspn();
strerror();
strlen();
strpbrk();
strrchr();
strspn();
strstr();
strtok();
strxfrm();
2.14.1VariablesandDefinitions
size_tistheunsignedintegerresultofthesizeofkeyword.
NULListhevalueofanullpointerconstant.
2.14.2memchr
Declaration:
void *memchr(const void *str, int c, size_t n);
Searchesforthefirstoccurrenceofthecharacterc(anunsigned char)inthe
firstnbytesofthestringpointedtobytheargumentstr.
Returnsapointerpointingtothefirstmatchingcharacter,ornullifnomatchwas
found.
2.14.3memcmp
Declaration:
int memcmp(const void *str1, const void *str2, size_t n);
Comparesthefirstnbytesofstr1andstr2.Doesnotstopcomparingevenafterthe
nullcharacter(italwayschecksncharacters).
Returnszeroifthefirstnbytesofstr1andstr2areequal.Returnslessthanzeroor
greaterthanzeroifstr1islessthanorgreaterthanstr2respectively.
2.14.4memcpy
Declaration:
void *memcpy(void *str1, const void *str2, size_t n);
Copiesncharactersfromstr2tostr1.Ifstr1andstr2overlapthebehavioris
undefined.
Returnstheargumentstr1.
2.14.5memmove
Declaration:
void *memmove(void *str1, const void *str2, size_t n);
Copiesncharactersfromstr2tostr1.Ifstr1andstr2overlaptheinformationisfirst
completelyreadfromstr1andthenwrittentostr2sothatthecharactersarecopied
correctly.
Returnstheargumentstr1.
2.14.6memset
Declaration:
void *memset(void *str, int c, size_t n);
Copiesthecharacterc(anunsigned char)tothefirstncharactersofthestring
pointedtobytheargumentstr.
Theargumentstrisreturned.
2.14.7strcat
Declaration:
char *strcat(char *str1, const char *str2);
Appendsthestringpointedtobystr2totheendofthestringpointedtobystr1.The
terminatingnullcharacterofstr1isoverwritten.Copyingstopsoncetheterminating
nullcharacterofstr2iscopied.Ifoverlappingoccurs,theresultisundefined.
Theargumentstr1isreturned.
2.14.8strncat
Declaration:
char *strncat(char *str1, const char *str2, size_t n);
Appendsthestringpointedtobystr2totheendofthestringpointedtobystr1up
toncharacterslong.Theterminatingnullcharacterofstr1isoverwritten.Copying
stopsoncencharactersarecopiedortheterminatingnullcharacterofstr2iscopied.
Aterminatingnullcharacterisalwaysappendedtostr1.Ifoverlappingoccurs,the
resultisundefined.
Theargumentstr1isreturned.
2.14.9strchr
Declaration:
char *strchr(const char *str, int c);
Searchesforthefirstoccurrenceofthecharacterc(anunsignedchar)inthestring
pointedtobytheargumentstr.Theterminatingnullcharacterisconsideredtobe
partofthestring.
Returnsapointerpointingtothefirstmatchingcharacter,ornullifnomatchwas
found.
2.14.10strcmp
Declaration:
int strcmp(const char *str1, const char *str2);
Comparesthestringpointedtobystr1tothestringpointedtobystr2.
Returnszeroifstr1andstr2areequal.Returnslessthanzeroorgreaterthanzero
ifstr1islessthanorgreaterthanstr2respectively.
2.14.11strncmp
Declaration:
int strncmp(const char *str1, const char *str2, size_t n);
Comparesatmostthefirstnbytesofstr1andstr2.Stopscomparingafterthenull
character.
Returnszeroifthefirstnbytes(ornullterminatedlength)ofstr1andstr2areequal.
Returnslessthanzeroorgreaterthanzeroifstr1islessthanorgreater
thanstr2respectively.
2.14.12strcoll
Declaration:
int strcoll(const char *str1, const char *str2);
Comparesstringstr1tostr2.TheresultisdependentontheLC_COLLATEsettingofthe
location.
Returnszeroifstr1andstr2areequal.Returnslessthanzeroorgreaterthanzero
ifstr1islessthanorgreaterthanstr2respectively.
2.14.13strcpy
Declaration:
char *strcpy(char *str1, const char *str2);
Copiesthestringpointedtobystr2tostr1.Copiesuptoandincludingthenull
characterofstr2.Ifstr1andstr2overlapthebehaviorisundefined.
Returnstheargumentstr1.
2.14.14strncpy
Declaration:
char *strncpy(char *str1, const char *str2, size_t n);
Copiesuptoncharactersfromthestringpointedtobystr2tostr1.Copyingstops
whenncharactersarecopiedortheterminatingnullcharacterinstr2isreached.If
thenullcharacterisreached,thenullcharactersarecontinuallycopied
tostr1untilncharactershavebeencopied.
Returnstheargumentstr1.
2.14.15strcspn
Declaration:
size_t strcspn(const char *str1, const char *str2);
Findsthefirstsequenceofcharactersinthestringstr1thatdoesnotcontainany
characterspecifiedinstr2.
Returnsthelengthofthisfirstsequenceofcharactersfoundthatdonotmatch
withstr2.
2.14.16strerror
Declaration:
char *strerror(int errnum);
Searchesaninternalarrayfortheerrornumbererrnumandreturnsapointertoan
errormessagestring.
Returnsapointertoanerrormessagestring.
2.14.17strlen
Declaration:
size_t strlen(const char *str);
Computesthelengthofthestringstruptobutnotincludingtheterminatingnull
character.
Returnsthenumberofcharactersinthestring.
2.14.18strpbrk
Declaration:
char *strpbrk(const char *str1, const char *str2);
Findsthefirstcharacterinthestringstr1thatmatchesanycharacterspecified
instr2.
Apointertothelocationofthischaracterisreturned.Anullpointerisreturnedifno
characterinstr2existsinstr1.
Example:
#include<string.h>
#include<stdio.h>

int main(void)
{
char string[]="Hi there, Chip!";
char *string_ptr;

while((string_ptr=strpbrk(string," "))!=NULL)
*string_ptr='-';

printf("New string is \"%s\".\n",string);


return 0;
}
Theoutputshouldresultineveryspaceinthestringbeingconvertedtoadash().
2.14.19strrchr
Declaration:
char *strrchr(const char *str, int c);
Searchesforthelastoccurrenceofthecharacterc(anunsignedchar)inthestring
pointedtobytheargumentstr.Theterminatingnullcharacterisconsideredtobe
partofthestring.
Returnsapointerpointingtothelastmatchingcharacter,ornullifnomatchwas
found.
2.14.20strspn
Declaration:
size_t strspn(const char *str1, const char *str2);
Findsthefirstsequenceofcharactersinthestringstr1thatcontainsanycharacter
specifiedinstr2.
Returnsthelengthofthisfirstsequenceofcharactersfoundthatmatchwithstr2.
Example:
#include<string.h>
#include<stdio.h>

int main(void)
{
char string[]="7803 Elm St.";

printf("The number length is %d.\n",strspn(string,"1234567890"));

return 0;
}
Theoutputshouldbe:Thenumberlengthis4.
2.14.21strstr
Declaration:
char *strstr(const char *str1, const char *str2);
Findsthefirstoccurrenceoftheentirestringstr2(notincludingtheterminatingnull
character)whichappearsinthestringstr1.
Returnsapointertothefirstoccurrenceofstr2instr1.Ifnomatchwasfound,thena
nullpointerisreturned.Ifstr2pointstoastringofzerolength,thenthe
argumentstr1isreturned.
2.14.22strtok
Declaration:
char *strtok(char *str1, const char *str2);
Breaksstringstr1intoaseriesoftokens.Ifstr1andstr2arenotnull,thenthe
followingsearchsequencebegins.Thefirstcharacterinstr1thatdoesnotoccur
instr2isfound.Ifstr1consistsentirelyofcharactersspecifiedinstr2,thennotokens
existandanullpointerisreturned.Ifthischaracterisfound,thenthismarksthe
beginningofthefirsttoken.Itthenbeginssearchingforthenextcharacterafterthat
whichiscontainedinstr2.Ifthischaracterisnotfound,thenthecurrenttoken
extendstotheendofstr1.Ifthecharacterisfound,thenitisoverwrittenbyanull
character,whichterminatesthecurrenttoken.Thefunctionthensavesthefollowing
positioninternallyandreturns.
Subsequentcallswithanullpointerforstr1willcausethepreviouspositionsavedto
berestoredandbeginssearchingfromthatpoint.Subsequentcallsmayusea
differentvalueforstr2eachtime.
Returnsapointertothefirsttokeninstr1.Ifnotokenisfoundthenanullpointeris
returned.
Example:
#include<string.h>
#include<stdio.h>

int main(void)
{
char search_string[]="Woody Norm Cliff";
char *array[50];
int loop;

array[0]=strtok(search_string," ");
if(array[0]==NULL)
{
printf("No test to search.\n");
exit(0);
}

for(loop=1;loop<50;loop++)
{
array[loop]=strtok(NULL," ");
if(array[loop]==NULL)
break;
}

for(loop=0;loop<50;loop++)
{
if(array[loop]==NULL)
break;
printf("Item #%d is %s.\n",loop,array[loop]);
}

return 0;
}
Thisprogramreplaceseachspaceintoanullcharacterandstoresapointertoeach
substringintothearray.Itthenprintsouteachitem.
2.14.23strxfrm
Declaration:
size_t strxfrm(char *str1, const char *str2, size_t n);
Transformsthestringstr2andplacestheresultintostr1.Itcopiesat
mostncharactersintostr1includingthenullterminatingcharacter.The
transformationoccurssuchthatstrcmpappliedtotwoseparateconvertedstrings
returnsthesamevalueasstrcollappliedtothesametwostrings.Ifoverlapping
occurs,theresultisundefined.
Returnsthelengthofthetransformedstring(notincludingthenullcharacter).

2.15time.h

Thetimeheaderprovidesseveralfunctionsusefulforreadingandconvertingthe
currenttimeanddate.SomefunctionsbehaviorisdefinedbytheLC_TIMEcategoryof
thelocationsetting.
Macros:

NULL
CLOCKS_PER_SEC
Variables:
typedef size_t
typedef clock_t
typedef size_t
struct tm
Functions:
asctime();
clock();
ctime();
difftime();
gmtime();
localtime();
mktime();
strftime();
time();
2.15.1VariablesandDefinitions
NULListhevalueofanullpointerconstant.
CLOCKS_PER_SECisthenumberofprocessorclockspersecond.
size_tistheunsignedintegerresultofthesizeofkeyword.
clock_tisatypesuitableforstoringtheprocessortime.
time_tisatypesuitableforstoringthecalendartime.
struct tmisastructureusedtoholdthetimeanddate.Itsmembersareasfollows:
int tm_sec; /* seconds after the minute (0 to 61) */
int tm_min; /* minutes after the hour (0 to 59) */
int tm_hour; /* hours since midnight (0 to 23) */
int tm_mday; /* day of the month (1 to 31) */
int tm_mon; /* months since January (0 to 11) */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday (0 to 6 Sunday=0) */
int tm_yday; /* days since January 1 (0 to 365) */
int tm_isdst; /* Daylight Savings Time */
Iftm_isdstiszero,thenDaylightSavingsTimeisnotineffect.Ifitisapositivevalue,
thenDaylightSavingsTimeisineffect.Ifitisnegative,thenthefunctionusingitis
requestedtoattempttocalculatewhetherornotDaylightSavingsTimeisineffect
forthegiventime.
Notethattm_secmaygoashighas61toallowforuptotwoleapseconds.
2.15.2asctime
Declaration:
char *asctime(const struct tm *timeptr);
Returnsapointertoastringwhichrepresentsthedayandtimeofthe
structuretimeptr.Thestringisinthefollowingformat:
DDD MMM dd hh:mm:ss YYYY
DDD Dayoftheweek(Sun,Mon,Tue,Wed,Thu,Fri,Sat)
MMM Monthoftheyear(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)
dd Dayofthemonth(1,...,31)
hh Hour(0,...,23)
mm Minute(0,...,59)
ss Second(0,...,59)
YYYY Year

Thestringisterminatedwithanewlinecharacterandanullcharacter.Thestringis
always26characterslong(includingtheterminatingnewlineandnullcharacters).
Apointertothestringisreturned.
Example:
#include<time.h>
#include<stdio.h>

int main(void)
{
time_t timer;

timer=time(NULL);
printf("The current time is %s.\n",asctime(localtime(&timer)));
return 0;
}
2.15.3clock
Declaration:
clock_t clock(void);
Returnstheprocessorclocktimeusedsincethebeginningofanimplementation
definedera(normallythebeginningoftheprogram).Thereturnedvaluedivided
byCLOCKS_PER_SECresultsinthenumberofseconds.Ifthevalueisunavailable,then1
isreturned.
Example:
#include<time.h>
#include<stdio.h>

int main(void)
{
clock_t ticks1, ticks2;
ticks1=clock();
ticks2=ticks1;
while((ticks2/CLOCKS_PER_SEC-ticks1/CLOCKS_PER_SEC)<1)
ticks2=clock();

printf("Took %ld ticks to wait one second.\n",ticks2-ticks1);


printf("This value should be the same as CLOCKS_PER_SEC which is
%ld.\n",CLOCKS_PER_SEC);
return 0;
}
2.15.4ctime
Declaration:
char *ctime(const time_t *timer);
Returnsastringrepresentingthelocaltimebasedontheargumenttimer.Thisis
equivalentto:
asctime(locatime(timer));
Thereturnedstringisinthefollowingformat:
DDD MMM dd hh:mm:ss YYYY
DDD Dayoftheweek(Sun,Mon,Tue,Wed,Thu,Fri,Sat)
MMM Monthoftheyear(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)
dd Dayofthemonth(1,...,31)
hh Hour(0,...,23)
mm Minute(0,...,59)
ss Second(0,...,59)
YYYY Year

Thestringisterminatedwithanewlinecharacterandanullcharacter.Thestringis
always26characterslong(includingtheterminatingnewlineandnullcharacters).
Apointertothestringisreturned.
2.15.5difftime
Declaration:
double difftime(time_t time1, time_t time2);
Calculatesthedifferenceofsecondsbetweentime1andtime2(time1time2).
Returnsthenumberofseconds.
2.15.6gmtime
Declaration:
struct tm *gmtime(const time_t *timer);
ThevalueoftimerisbrokenupintothestructuretmandexpressedinCoordinated
UniversalTime(UTC)alsoknownasGreenwichMeanTime(GMT).
Apointertothestructureisreturned.AnullpointerisreturnedifUTCisnot
available.
2.15.7localtime
Declaration:
struct tm *localtime(const time_t *timer);
Thevalueoftimerisbrokenupintothestructuretmandexpressedinthelocaltime
zone.
Apointertothestructureisreturned.
Example:
#include<time.h>
#include<stdio.h>

int main(void)
{
time_t timer;

timer=time(NULL);
printf("The current time is %s.\n",asctime(localtime(&timer)));
return 0;
}
2.15.8mktime
Declaration:
time_t mktime(struct tm *timeptr);
Convertsthestructurepointedtobytimeptrintoatime_tvalueaccordingtothe
localtimezone.Thevaluesinthestructurearenotlimitedtotheirconstraints.If
theyexceedtheirbounds,thentheyareadjustedaccordinglysothattheyfitwithin
theirbounds.Theoriginalvaluesoftm_wday(dayoftheweek)andtm_yday(dayof
theyear)areignored,butaresetcorrectlyaftertheothervalueshavebeen
constrained.tm_mday(dayofthemonth)isnotcorrecteduntil
aftertm_monandtm_yeararecorrected.
Afteradjustmentthestructurestillrepresentsthesametime.
Theencodedtime_tvalueisreturned.Ifthecalendartimecannotberepresented,
then1isreturned.
Example:
#include<time.h>
#include<stdio.h>

/* find out what day of the week is January 1, 2001


(first day of the 21st century) */

int main(void)
{
struct tm time_struct;
char days[7][4]={"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

time_struct.tm_year=2001-1900;
time_struct.tm_mon=0;
time_struct.tm_mday=1;
time_struct.tm_sec=0;
time_struct.tm_min=0;
time_struct.tm_hour=0;
time_struct.tm_isdst=-1;

if(mktime(&time_struct)==-1)
{
printf("Error getting time.\n");
exit(0);
}

printf("January 1, 2001 is a %s.\n",days[time_struct.tm_wday]);


return 0;
}
2.15.9strftime
Declaration:
size_t strftime(char *str, size_t maxsize, const char *format, const struct
tm *timeptr);
Formatsthetimerepresentedinthestructuretimeptraccordingtotheformatting
rulesdefinedinformatandstoredintostr.Nomorethanmaxsizecharactersare
storedintostr(includingtheterminatingnullcharacter).
Allcharactersintheformatstringarecopiedtothestrstring,includingthe
terminatingnullcharacter,exceptforconversioncharacters.Aconversioncharacter
beginswiththe%signandisfollowedbyanothercharacterwhichdefinesaspecial
valuethatitistobereplacedby.
Conversion Whatitisreplacedby
Character
%a abbreviatedweekdayname
%A fullweekdayname
%b abbreviatedmonthname
%B fullmonthname
%c appropriatedateandtimerepresentation
%d dayofthemonth(0131)
%H houroftheday(0023)
%I houroftheday(0112)
%j dayoftheyear(001366)
%m monthoftheyear(0112)
%M minuteofthehour(0059)
%p AM/PMdesignator
%S secondoftheminute(0061)
%U weeknumberoftheyearwhereSundayisthefirstdayofweek1(00
53)
%w weekdaywhereSundayisday0(06)
%W weeknumberoftheyearwhereMondayisthefirstdayofweek1(00
53)
%x appropriatedaterepresentation
%X appropriatetimerepresentation
%y yearwithoutcentury(0099)
%Y yearwithcentury
%Z timezone(possiblyabbreviated)ornocharactersiftimezone
isunavailable
%% %
Returnsthenumberofcharactersstoredintostrnotincludingtheterminatingnull
character.Onerrorzeroisreturned.

2.15.10time
Declaration:
time_t time(time_t *timer);
Calculatesthecurrentcalendertimeandencodesitintotime_tformat.
Thetime_tvalueisreturned.Iftimerisnotanullpointer,thenthevalueisalso
storedintotheobjectitpointsto.Ifthetimeisunavailable,then1isreturned.

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