Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming...
Transcript of Introduc)on to the C programming Language · 2018. 1. 24. · Introduc)on to the C programming...
Introduc)ontotheCprogrammingLanguage
Prak)kumKernelProgrammingUniversityofHamburgScien)ficCompu)ng
Wintersemester2015/2016
Konstan)nosChasapisKonstan)nos.chasapis@informa)k.uni-hamburg.de
Outline
• HelloWorld• Preprocessor/Compiler/Linker• Thebasis• Pointers• MemoryLayout/alloca)on• Structures/unions• Inlineassembly
Introduction to C 21/10/15 1
HelloWorld• Preprocessor
– cpp– #include<stdio.h>
• mainfunc)on– Getstwoarguments
• argc,the#ofcommandlinearguments• argv,stringsofthecommandlinearguments
– Returnsanintegertodenotetheexecu)onstatus• 0insuccessfullexecu)on
• PrinV– Printstothestandardoutput
Introduction to C
#include<stdio.h>intmain(intargc,char*arv[]){printf("Helloworld!\n");return0;}
21/10/15 2
Preprocessor(cpp)• Executesbeforethecompila)on• Includeheaderfiles
– #include<filename.h>– <>-searchinstandarddirectories– “”pathtothefile
• Macrosexpansion– #defineEXTVALUE– #undefEXT
• Condi)onalCompila)on– #if,#elif,#endif– #ifdef,#ifndef
Introduction to C 21/10/15 3
Preprocessor(cpp)
• Otherdirec)ves– #Replacesamacroparameterwithastringconstant
– ##Tokenmerge,createsasingletokenfromtwoadjacentones
• Macroscon)nua)on(\)– #defineLONG_MACRO\
Expand_also_here
Introduction to C 21/10/15 4
Preprocessor(cpp)
• Usefulpredefinedmacros__DATE__
• Currentdateasastringwith"MMMDDYYYY”format__TIME__
• Current)measstringwith"HH:MM:SS“format__FILE__
• Currentfilenameasastring__LINE__
• Currentlinenumberasanumber
• hops://gcc.gnu.org/onlinedocs/cpp/
Introduction to C 21/10/15 5
Compile• Manyopensourcecompilers• gcc(GNUCompilerCollec)on)
-c,createsanobjectfile• $filename.o
-o,nametheexecutable• defaultnamea.out
-g,adddebugginginforma)on-Wall,enablesallwarnings
• gcc-ohello_worldhello_world.c• hop://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html
Introduction to C 21/10/15 6
Createtheexecutable• Cpreprocessor
– Passpreprocessordirec)ves• Compila)on
– Csourcecodeintoassemblycode– Checkforsyntaxerrors
• Assembling– Assemblysourcecodeintoassemblylis)ngwithoffsets
• Linking– Takesoneormanyobjectfilesandlibrariestocreateasingleexecutable
source code.c
source code.i
source code.s
source code.o
executable
Introduction to C 21/10/15 7
Outline
• HelloWorld• Preprocessor/Compiler/Linker• Thebasis• Pointers• MemoryLayout/alloca)on• Structures/unions• Inlineassembly
Introduction to C 21/10/15 8
Iden)fiersnames
• Usetoiden)fy– Variablenames– Func)onnames– Otheruser-defineditems
• Format– StartswithA-Z,a-z– Followedbyleoers,digits,underscores_– Casesensi)ve
Introduction to C 21/10/15 9
Variablesbasicdatatypes• int,integers
– signed– unsigned– short– longlong– char,characters
• signedchar,-128..127• unsignedchar,0..256
• floa)ngpoint(IEE754standard)– float,singledprecision– double,doubleprecision
Introduction to C 21/10/15 10
voidtype• Mul)plemeanings• Whenusedinfunc)onargumentlist
– funct(void)– Doesnotacceptanyargument
• Returnvalueofafunc)on– voidfucnt(..)– Doesnotreturnanyvalue
• Pointertoavalue– void*v_pointer;– pointstounspeciateddatatype
Introduction to C 21/10/15 11
Variablesqualifiers
• Const– Variablecannotchangeazerini)aliza)on– constfloatpi=3.14;
• Vola)le– Extremeoppositeofconst.– Indicatesthatavariablemaybechangedinaway– Everyreferencetothevariablewillreloadthecontentsfrommemory
– vola)leintv;
Introduction to C 21/10/15 12
enumdatatype
• Abbrevia)onforenumerate• Declareandini)alizeasequenceofintegerconstants
• Example:– enumcolors{RED,YELLOW,GREEN};– enumcolors{RED=0,YELLOW=1,GREEN=2};
Introduction to C 21/10/15 13
VariableStorageClass• auto
– Defaultforstoringthelocalvariables• register
– LocalvariablesthatshouldbestoredinregistersinsteadofRAM
– fastaccess• sta)c,twomeanings
– Globalvariables,canbeseeninthisfileonly.– Localvariables,ini)alizedonce,retainsvalueduringvariouscalls
• extern– Makeaglobalvariablevisibletoallprogramfiles
Introduction to C 21/10/15 14
Variablessize-sizeof()
• Specialoperatorreturnsthesizeinchar• Examples
– sizeof(char)//1– sizeof(int)//4– sizeof(float)//4– sizeof(double)//8
Introduction to C 21/10/15 15
Arrays
• Madefromelementsofbasictypes• Usesquarebrackets[]todeclarethem• Canhavemul)pledimensions• Cannotchangesizeduringexecu)on)me• Allocatedsequen)ally• Startfrom0• Examples
– inta[3]={1,2,3};– charstrings[2][5]={“this”,“is”,“test”};
Introduction to C 21/10/15 16
Strings
• Specialcaseofchararrays• Nullterminated• Example:
– charstring[5];• string[0]=`t`;• string[1]=`e`;• string[2]=`s`;• string[3]=`t`;• String[4]=`\0`;
Introduction to C 21/10/15 17
Variablescope• Global
– Definedoutsideofablock/func)on– Canbeaccessedbyanyfunc)on/block– Retainvalueduringtheprogramexecu)on
• Local– Definedinsideablock(compoundstatement)– Mainlyinthetopofthefunc)on/block– Usedonlyinthisblock– Overwritesglobalvariableswiththesamename– Losevalueattheendofthefunc)on/block
• Formal– Func)onparameters,usedaslocalvariables
Introduction to C 21/10/15 18
Constants• Numericvalues
– Octalstartswith0,015– Hexadecimalstartswith0x,0xA1– LongendswithL,12312341124L
• Characters– \n, newline– \t, tab– \\, backslash– \’’, singlequote– \0, stringterminatecharacter– NULL,integervalueof0
Introduction to C 21/10/15 19
Operators• Arithme)cOperators
– +,-,*,/,%,++,--• LogicalOperators
– ==,!=,<=,<,>=,>,!,&&,||• BitwiseOperators
– &,|,^,~,<<,>>• AssignmentOperators
– =,+=,-=,*=,/=,%=,&=,^=,|=• MiscOperators
– sizeof(),&,*,?=
Introduction to C 21/10/15 20
Statements
• Expressionstatements– Expressionfollowedbysemicolon;
• a=1+3;• Compoundstatements
– Oneormorestatementsenclosedbyapairofbraces{}
• {pi=3.14;area=pi*radios*radios;}• Controlstatements
– Controltheexecu)onflow• if,else,case,foretc.
Introduction to C 21/10/15 21
Condi)onalstatementsContrac)on
• if(expression)statement;– ifexpressionevaluatedasnonzeroenterstheifstatement
• Exampleif(a<X){code_block}elseif(a>X){code_block}else{code_block}
Introduction to C 21/10/15 22
Condi)onalstatementsContrac)on
switch(expression){caseconstant-expr1:statement1;[caseconstant-expr2:statement2;]default:statement3;
}• Firstevaluatesexpression• Thenentersthecasethatmatchestheexpressionvalues• Otherwiseexecutesthedefault• Con)nuestheexecu)onun)litfindsbreak;
Introduction to C 21/10/15 23
Condi)onalstatementsContrac)on
• Checkifvariable“a”isequaltoXorYorZ
switch(a){ caseX:{codeblock} caseY:{codeblock} caseZ:{codeblock} default: //noteqaultoX,Y,Z}
Introduction to C 21/10/15 24
Looping-for
• for(expr1;expr2;expr3){compoundstatements}– Executestheexpr1inthebeginning– Evaluatestheexpr2andifnonzeroexecutesthecompoundstatements
– Attheendexecutestheexpr3andreevaluatestheexpr2con)nuesun)lexpr2iszero.
• Examplefor(i=0;i<ARRAYSIZE;i++){ codeblock;}
Introduction to C 21/10/15 25
Looping-while
• while(expression){compoundstatements}– Evaluatesexpressionandifnonzeroexecutesthecompoundstatementsun)lexpressionisnonzero
• Examplei=0;while(i<ARRAYSIZE){ codeblock; i++;}
Introduction to C 21/10/15 26
Looping–dowhile
• do{compoundstatements}while(expression);
– Executesthecompoundstatements– Evaluatestheexpressionandifnonzerorepeats
• Exampledo{ i++;}while(i<ARRAY_SIZE);
Introduction to C 21/10/15 27
breakandcon)nue
while(i<10){i=i+1;if(i<10)con)nue; i=0;break;
}
• break– Exitsalooporacasestatement
• con)nue– Con)nuestheexecu)onfromthebeginningoftheloop
switch(a){caseZ:{codeblock
break;}caseY:{codeblock}caseX:{codeblock}
}
Introduction to C 21/10/15 28
Commnets
• Singlelinecomments– //comments
• Mul)plelinescomments– /*comments*/
Introduction to C 21/10/15 29
Func)ons• Madeupbyfourcomponents
– Returnvalue– Func)onname– Argumentslist– Func)onbody
• Example– intfunc)on_name(inta,intb){returna+b;}
• Parameters– Callbyvalue,copiesthevalueoftheargumenttotheformalparameter
– Callbyreference,copiestheaddressoftheargumenttoformalparameter
Introduction to C 21/10/15 30
Func)onsexamples
• Returnsanintegergetsnoargument– intfoo(void);
• Returnsthesumoftwofloats– floatfloat_sum(floata,floatb){returna+b;}
Introduction to C 21/10/15 31
Outline
• HelloWorld• Preprocessor/Compiler/Linker• Thebasis• Pointers• MemoryLayout/alloca)on• Structures/unions• Inlineassembly
Introduction to C 21/10/15 32
Pointers• Variablestoreaddresses
– variableaddresses– func)ons
• Declara)on– type*name;//variable– type(*f_name)(..);//func)onpointer
• Examples– int*p_i;//pointertoanint– double*p_d;//pointertodouble– void(*p_f)(int);//func)onpointertoafunc)onthatreturnsvoidandhasanintegerparameter
Introduction to C 21/10/15 33
Pointerscont.
• Dereference– Getthevalueofthevariablepointerpointsto– Use(*)
• Addressofavariable– Use(&)
• Exampleinta=1;int*p_a=&a; 0x 111077AB
1 0x 111077AB a
p_a
Introduction to C 21/10/15 34
Pointerstypecas)ng
• Convertavariablefromonetypetoanother• Usedtocastvoid*• Examples void*v;int*a; v=(void*)a; a=(int*)v;
Introduction to C 21/10/15 35
Pointersexample• Func)onthatwillswapthevalueoftwointegervariablesvoidswap(int*a,int*b){ inttmp; tmp=*a;//storethevaluethatapointstoattmp *a=*b; *b=tmp;}
• Howtocallthefunc)oninta=3,b=4;swap(&a,&b);
Introduction to C 21/10/15 36
MemoryLayout• textsegment
– Sourcecode• datasegment
– Globalvariables– Sta)cvariables
• heap– Dynamicallyallocatedmemory
• stack– Localvariables– Func)onparameters
text segment
data segment
heap
unallocated
stack
low address
high address Introduction to C 21/10/15 37
Stackalloca)on• stackpointer(sp)
– topofthestack
g(){;}
f(){g();
}
main(){f();
}main() main()
f()
sp
sp
sp
params
main()
f() params
params g()
Introduction to C 21/10/15 38
Heapalloca)on
• Stackallocatessta)csizevariables– Sizeknowedatcompile)me
• Dynamicallymemorystoredinheap• Allocateusing
– malloc()//allocatesrequestedamount– calloc()//allocatesandzerosmemory
• Youhavetoexplicitlyfreethememory– Doesnothavegarbagecollec)on– free()
Introduction to C 21/10/15 39
Heapalloca)onExamples
• Allocateanarrayof10integersint*a;a=(int*)malloc(10*sizeof(int));free(a);
• Allocateanarrayof10floatsandzerothemfloat*a;a=(float*)calloc(10,sizeof(float));free(a);
Introduction to C 21/10/15 40
Outline
• HelloWorld• Preprocessor/Compiler/Linker• Thebasis• Pointers• MemoryLayout/alloca)on• Structures/unions• Inlineassembly
Introduction to C 21/10/15 41
Structures• Collec)onofitemsofdifferenttypes
– Itemscalledmembers/fields• SimilartoClassesofJava• Example structperson{
charname[255]; intheight;}
• Accessstructmembers– Forreference/pointertoastructuse->
• structperson*p_person;p_person->height;– Fortheactualstructuse.
• structpersonperson;person.height;
Introduction to C 21/10/15 42
Unions• Storedifferentdatatypeinasinglememoryloca)on
• Similardefini)onsofstructs• Example
unionData{inti;floatf;charstr[20];}
• Accessfieldsusing.– Data.i=3;
Introduction to C 21/10/15 43
Typedef
• Nameanewtype• Mainlyusedforstructbutnotlimited• Syntax
– typedeftypetype_name
• Examples– typedefunsignedcharBYTE;– typedefstructpersonperson_t;
Introduction to C 21/10/15 44
Inlineassembly• asm-gccextension
– ReadandwriteCvariablesfromassembler– PerformjumpsfromassemblercodetoClabels– Foransiandstduse_asm_
• Basicsyntax– asm[vola)le](AssemblerInstruc)ons)– Addmul)pleassemblylineswith‘\n\t’
• Extendedasmsyntax– asm[vola)le](AssemblerTemplate:OutputOperands[:InputOperands[:Clobbers]])
Introduction to C 21/10/15 45
asmexamples
• Copysrctodstandadd1todst– asm("mov%1,%0\n\t""add$1,%0":"=r"(dst):"r"(src));
Introduction to C 21/10/15 46
Keywords
externreturnunioncharfloatshortunsignedconstfor
signedvoidcon)nuegotosizeofvola)ledefaultifsta)c
whiledointstructdouble
Introduction to C
autoelselongswitchbreakenumregistertypedefcase21/10/15 47
Ques)ons?
Konstan)nosChasapis
Konstan)nos.chasapis@informa)k.uni-hamburg.de
Introduction to C 21/10/15 48