Lecture_16 - ECE190 Lecture16 March9,2011 Lecture Topics IntroductiontousingfunctionsinC Syntax Examples

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ECE190 Lecture16 March9,2011 Lecture Topics IntroductiontousingfunctionsinC Syntax Examples Memoryallocationforvariables Lecture materials Textbook§14.1 ­14.2,12.5 Homework Machine problem MP3.2dueMarch18,2011at5pmsubmittedelectronically. Announcements Examsnextweek     1 V.Kindratenko ECE190 Lecture16 March9,2011 Introduction to functions in C  AfunctioninCisroughlyequivalenttoasubroutineinLC ­3assemblylanguage  Itisasegmentofcodethatimplementssomewell ­definedfunctionintheprogram  ExamplefromMP3 o Clearboard o Setupboard o Displayboard  Allthesearefunctionsthatdosomewell ­definedwork.  Themainprogramthenjustcallsthemwhenneeded  Usingfunctionsenables o Hidinglow ­leveldetails o Givinghigh ­levelstructuretotheprogram o Efficientlyreusingcode Syntax  UsingfunctionsinCrequires:  1.Afunctionprototype,orfunction sdeclaration o NotewedidnotneedoneinLC ­3assemblylanguage o Example:intFactorial(intn); o Functionprototypespecifiesthreethings:  Nameofthedunction,e.g.,sin,cons,printf,Factorial,etc.  Typesofallargumentsthatarepassedtothefunction,e.g.,intforninthe exampleabove  Typeofreturnvalue o Examples:  doublecos(doublex);< ­cosfunctionrequiresoneargumentoftypedouble andreturnsavalueoftypedouble  intgetchar(void);< ­readsacharacterformkeyboardandreturnsitsasciivalue; doesnotrequireanyarguments=noinput.  voidclearscreen(void);< ­clearsscreen,takesnoarguments,returnsnothing. o Afunctionmayreturnnovalue;inthiscaseitsreturntypeis void  o Afunctionmaynotrequireanyarguments;inthiscaseitsargumentslistisdeclaredas void  o Functionprototypemustbeprovidedbeforethefunctioniscalledintheprogram  2.Functiondefinitionorimplementation o NoteweneededthisinLC ­3assemblyaswell o Thisistheactualsourcecodeofthefunction o Itincludesaformallistofarguments alistofvariablesdeclaredandtheorderinwhich theyareexposedtotheuser o Example  2 V.Kindratenko ECE190 Lecture16 March9,2011 intFactorial(intn) { inti,result=1   for(i=0 i<=n i++) result=result*i   returnresult  } o Inthisexample,wehaveanimplementationofthefunctiontocomputefactorialof numbern.  Valueofnispassedtothefunctionasanargument.  Resultisreturnedbacktothecallingprogramusingreturnkeyword. o Tousethisfunction,weneedtojustcallitfromourmainfunction: #include<stdio.h> /*ourFactorialfunctionprototypegoeshere*/ intFactorial(intn)  /*mainfunction*/ intmain() { intnumber  intanswer  printf( Enteranumber: )  scanf( %d ,&number)  answer=Factorial(number) /*numberistheargument thatistransmittedfrom thecallingfunction(main) tothecalledfunction*/ printf( factorialof%dis%d\n ,number,answer)  return0  } /*implementationofFactorialfunctiongoeshere*/ More examples MP1.2example:convertthecomputationofsinfunctionintoanactualfunction.  Before:  3 V.Kindratenko ECE190 Lecture16 March9,2011 #include<stdio.h> #definePI3.141592653589793238462643  intmain() { doublex=0.0  doublesin_x=0.0  doubler=0.0  doublesin_x_num  doublesin_x_den  doubleerror  intn   /*getx(indegrees)andrfromtheuser*/ printf("Enterx(indegrees):")  scanf("%lf",&x)  printf("Enterthemaximumerror:")  scanf("%lf",&r)   /*correctthedomainofx*/ while(x< 180||x>180) x=(x>180)?x 360:x+360   /*convertsdegreestoradians*/ x*=PI/180   /*computethesineofx*/ n=1  sin_x_num=x  sin_x_den=1  sin_x=sin_x_num/sin_x_den  error=((sin_x_num*x*x)/(sin_x_den*(n+2)*(n+1)))   /*repeatpreviouscomputationiferrordoesnotequalr*/ while(error>r||error<( 1*r)) { n+=2  sin_x_num*=( 1)*(x*x)  sin_x_den*=n*(n 1)  sin_x+=sin_x_num/sin_x_den  error=((sin_x_num*x*x)/(sin_x_den*(n+2)*(n+1)))  }  /*printresultstotheterminal*/ printf("sin(%lf)=%lf\n",x,sin_x)   return0  }   After:  4 V.Kindratenko ECE190 Lecture16 March9,2011 #include<stdio.h> #definePI3.141592653589793238462643  doublemysin(doublex,doubler) /*functionprototype*/  intmain() { doublex=0.0  doublesin_x=0.0  doubler=0.0   /*getx(indegrees)andrfromtheuser*/ printf("Enterx(indegrees):")  scanf("%lf",&x)  printf("Enterthemaximumerror:")  scanf("%lf",&r)   /*correctthedomainofx*/ while(x< 180||x>180) x=(x>180)?x 360:x+360   /*convertsdegreestoradians*/ x*=PI/180   sin_x=mysin(x,r) /*calltoourfunction*/   /*printresultstotheterminal*/ printf("sin(%lf)=%lf\n",x,sin_x)   return0  }  doublemysin(doublex,doubler)/*functionimplementation*/ { doublesin_x_num  doublesin_x_den  doubleerror  intn   /*computethesineofx*/ n=1  sin_x_num=x  sin_x_den=1  sin_x=sin_x_num/sin_x_den  error=((sin_x_num*x*x)/(sin_x_den*(n+2)*(n+1)))   /*repeatpreviouscomputationiferrordoesnotequalr*/ while(error>r||error<( 1*r)) { n+=2   5 V.Kindratenko ECE190 } Lecture16 March9,2011 sin_x_num*=( 1)*(x*x)  sin_x_den*=n*(n 1)  sin_x+=sin_x_num/sin_x_den  error=((sin_x_num*x*x)/(sin_x_den*(n+2)*(n+1)))  }  returnsin_x  Memory allocation for variables  WhenaCcompilercompilesaprogram,itkeepstrackofvariablesinaprogramusingasymbol table.Wheneveritfindsanewvariabledeclaration,itcreatesanewentryinitssymboltable correspondingtothevariablebeingdeclared.  Symboltablecontainsenoughinformationforthecompilertoallocatestorageinmemoryfor thevariableandforthegenerationofthepropersequenceofmachinecodetoaccessthevalue ofthatvariablewhenitisusedintheprogram.  Eachentryinthesymboltablehas4items: o Nameofthevariable o Itstype o Placeinmemorythevariablehasbeenallocatedstorage o Identifierfortheblockinwhichthevariableisdeclared  ExampleforourMP4.2programwiththefunction: Variableidentifier(name) type Location(asanoffset) Scope x double 0 main sin_x double  ­1 main r double  ­2 main sin_x_num double 0 mysin sin_x_den double  ­1 mysin error double  ­2 mysin n int  ­3 mysin o 7variablestotal o Variable slocationinmemoryisrecordedasanoffsetwhichindicatesrelativeposition ofthevariablewithintheregionofmemoryitisallocated.  Thisindicateshowmanylocationsfromthebaseofthesectionavariableis allocatedstorage.  TherearetworegionsofmemoryinwhichCvariablesareallocatedstoragespace: o Globaldatasection  Whereallglobalvariablesarestored  Ormoregenerallywherevariablesofthestaticstorageclassareallocated o Run ­timestack  Wherelocalvariables(ofthedefaultautomaticstorageclass)areallocated  Wewilltalkaboutitinthenextlecture  6 V.Kindratenko ECE190 Lecture16 March9,2011  MemorymapforaCprogram Systemspace x3000 PC Programtext R4 Globaldatasection Heap (fordynamically allocatedmemory) Variablesofstaticstorage classarestoredintheglobal datasection Run ­timestackcontains activationrecords(orstack frames)forcalledfunctions R6(stackpointer) R5(framepointer) Run ­timestack Variablesofthedefault automaticstorageclassare storedintherun ­timestack space Systemspace   NoteuseofregistersR4,R5,andR6 o R4pointstothefirstaddressofmemoryallocatedforglobalvariables o R5containsstackpointer memoryregioninsidethefunction sactivationrecordwhere localvariablesarestored o R6containsaddressofthetopoftherun ­timestack  WhenwecallafunctioninC,itsactivationrecordispushedontotherun ­timestack  Wheneverafunctioncompletes,itsactivationrecordispoppedofftherun ­timestack  Function sactivationrecordcontainsallthedatalocaltothefunctioninvolvedinthefunction invocation,execution,andtransferoftheresultsbacktothecallingfunction o Itsexactstructuredependsonthecompilerimplementation;wewillstudyjustone particularexampleimplementation   7 V.Kindratenko ...
View Full Document

This note was uploaded on 01/22/2012 for the course ECE 191 taught by Professor Staff during the Spring '11 term at University of Illinois, Urbana Champaign.

Ask a homework question - tutors are online