lecture_03 - ECE190 Lecture03 January25,2011...

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 Lecture03 January25,2011 Lecture Topics IntroductiontoC VariablesinC Operators,expressions,statements BasicI/Owithprintfandscanf Lecture materials TextbookChapter11,§12.1.,12.2 Homework None  Machine problem None    1 V.Kindratenko ECE190 Lecture03 January25,2011 Introduction to C Overview Clanguagewasinventedin1972byDennisRitchieattheBellTelephoneLaboratoriesforuse withtheUnixoperatingsystem o Wasstandardizedin1988,thestandardiscalledANSIC(forAmericanNational StandardsInstitute) o In1990,theANSICstandardwithsomeminormodificationswasadoptedbythe InternationalOrganizationforStandardization.ThisversioniscalledC90 o ThelateststandardiscalledC99,itwasadoptedin2000byANSIfromISO o InthiscoursewewillstudyANSIC Cisageneral ­purposehigh ­levelcomputerprogramminglanguage o Providesanabstractionoftheunderlyinghardware o IsindependentofISA o Isexpressive,meaningthatcomplextaskscanbeexpressedwithasmallamountofcode o Ismuchmorereadablethanassemblycode symbolicnamesareusedinsteadofmemorylocationsandregisterstoreferto values operatorsareusedtomanipulatevalues butnotethatsomeoperatorsaretakendirectlyfromtheassembly language,e.g.++ Cisaprocedurallanguage o theprogrammerspecifiesanexplicitsequenceofstepstofollowtoproducearesult o theprogramiscomposedofprocedures,alsocalledafunction,orroutine,orsubroutine Cprogramsarecompiledratherthatinterpreted o CompilertranslatesaprogramwritteninCintomachinecodethatisdirectlyexecutable bytheprocessorforwhichitiscompiled o Forcomparison,interpretedprogramsareexecutedbyanotherprogram,called interpreted.Theyarenottranslatedintobinaryinstructions Basic C program structure ConsiderthefollowingCprogramexample: /*myfirstprogramwritteninC  itprintsthevalueofPIandexits*/ #include<stdio.h> #definePI3.1416f intmain() { floatpi=PI   pi=%f\ ,pi)  return0  }  2 V.Kindratenko ECE190 Lecture03 January25,2011 Comments o /*thisisacomment.Alltextincludingcarriagereturns isnotconsideredtobetexttobecompileduntilthe terminatingsymbolisreached,thatbeing */ pre ­processordirectivesbeginwith# o #include<stdio.h> Instructsthepre ­processortocopycontentofstdio.h(headerfile)intothe sourcecode stdio.hheaderfileincludesfunctiondeclarationsnecessarytousestandardI/O functionsinC almostallprogramswillneedtoincludethisheaderfile otherexamplesofincludefilesaremath.h,stdlib.h,etc. <stdio.h>andotherheaderfilesincludedin<>arelocatedinsomewell ­defined placeinthefilesystemknowntothecompiler Headerfileslocatedinthecurrentdirectoryorthedirectoryprovidedtothe compilerbytheuser  o #definePI3.1416 Directsthepre ­processortoreplaceallinstancesofstringPIinthefilebeing pre ­processedwiththevalueof3.1416 o #ifdefDEBUG ... #endif selectivelyincludetextinthefilebasedonwhetherasymbolDEBUGwas defined o #definemin(a,b)(a<b?a:b) Allowstodefinea"macro",sortoflikeanin ­linesubroutine mainfunction o "main"iswheretheprogramlogicbegins o Thisfunctioniscalledfirstwhenthecodeisexecuted o everyexecutableprogramhassomecomponentinitwherethisroutine"main"is declared;onlyonefilecompiledtocreatetheexecutablewillhaveit o functiondefinition,orimplementation,includesitsdeclaration,orprototype,(int main())andtheactualbody,orcodesurroundedby{} o mainfunctionhasreturntypeint,moreonthislaterinthecourse variables o variablesusedinsidemain(aswellasanyotherfunction)firstmustbedeclared o variabledeclarationrequiresprovidingitstypeandname Cimplements"strongtyping":thedatatype(andimplicitly,size)declared compilermapsthesetomemorylocationsautomatically o variablescanalsobeinitializedatthetimeofdeclaration o programreferstovariables,bytheirnames,e.g.,  3 V.Kindratenko ECE190 Lecture03 January25,2011 intA,B,C  A=5  B=10  C=A+B  o compilerautomaticallycreatessequencesofregister/memoryinstructionswhose ultimateeffectistoloadthememorylocationassociatedwithCwiththesumofthe valuesinmemorylocationstowhichAandBaremapped almostallprogramsperformsomesortofinputandoutput,whichcantakemanyforms,e.g., blinkinglightonthedashboard,outputonthedisplay,etc. o inatypicalCprogram,printffunctionisusedtooutputsometextorvaluetothedisplay \  variablepi,andthenwillprintnewlinecharacter o inatypicalCprogram,scanffunctionisusedtoreceivesomeinputfromtheuservia keyboard semicolon(;)isusedtoterminatedeclarationsandstatements C program compilation flow Csourcefile(.c) headerfiles(.h) Pre ­processor Csourcefile(.i) compiler libraries (.a) Objectfile(.o) linker Other object file (.o) executable  Pre ­processoractsuponpre ­processordirectives o scansthefileforpreprocessingdirectivesprefacedby# substitutespreprocessorsymbolswithactualvalues  4 V.Kindratenko ECE190 Lecture03 January25,2011 insertsheaders eliminatedsectionsofthecode,etc. o output:Csource(.i) Compilerincludestwophases o Analysisphase:aninternalrepresentationoftheprogramisbuilt recognizesdeclarationsofvariables,subroutines,recognizeslogicalconstructs ofC,e.g.,loops,conditionalexecution organizesallthisindatastructures looksforlogicalconsistency,e.g.,parametersinsubroutinecalls o Synthesisphase:machinecodeisgenerated constructsassemblylanguageprogram(.as)translation,oftenjustinternal emitsanobjectfile,(.o)comprisedofbinaryinstructions,atableofsymbols definedinthefile(e.g.,variables,namesofsub ­routines) o output:objectmodule(.o) Linker o combinesmultipleobjectfiles,librariesofsubroutines, createsmemorymapofvariablesandsymbols emitsfinalfileofexecutablecode o output:executablecode wewillusegcccompilerthatinvokesallthesetools(andmore)togeneratetheexecutable o gcc Wall ansi pedantic omyprogrammyprogram.c  ­Wallwillforcethecompilertoreportallerrorsandwarnings  ­ansiwillforcethecompilertoturnoffallfeaturesnotincludedintheANSI standard  ­pedanticwillcausethecompilertogenerateawarningforanynon ­ANSI featureitfindinourprogram  ­osomename thecompiledexecutablewillbesavedassomenamefile somename.cisthemaneofthesourcecode,canbemultiplefiles o  o toexecutethecompiledprogramsavedinsomenamefile,type./somenameintheLinux shellwhileinthesamedirectorywheretheexecutableislocated Variables in C VariablesinCprogramholdvaluesuponwhichaprogramacts o Callowstheprogrammertorefertovaluessymbolically,byname Inanassemblylanguagethisistypicallydonebymemoryaddress Beforeavariablecanbeusedintheprogram,itmustbedeclared o variabledeclarationrequiresprovidingatleastitstypeandname(<type><name>;) variabletypeisusedbythecompilertofigureouthowmuchmemoryto allocateforstoringthevariableandhowtointerpretitsvalue variablenameisusedtosymbolicallyaccessvaluesthroughouttheprogram  5 V.Kindratenko ECE190 Lecture03 January25,2011 namecanbeanycombinationofcharacters,digits,andsomespecial characters,suchas_ o uptosomenumberofcharacters o cannotstartfromadigit o case ­sensitive o threebasicdatatypesinC int ­ itssize(numberofbits)ismachine ­ dependent;holdsanintegervalue short 16 ­ lementinteger long 32 ­  longlong 64 ­  unsignedmodifiercanbeusedtoindicatethatthenumberis representedusingunsignednotation float 32 ­bitfloating ­pointrepresentation;holdsarealvalue double 64 ­bitfloating ­pointrepresentation char 8 ­bitrepresentationusedtostoreavalueofacharacter(ASCIIvalue) someoftheextendeddatatypesareonlyavailablewhentheunderlyingISA supportsthem o variablecanbedeclaredusingconstantqualifiertoindicatethatitsvaluedoesnot changeduringtheexecutionoftheprogram o variablescanalsobeinitializedatthetimeofdeclaration inta=10  constfloatpi=3.1416f or constfloatpi=PI inthiscase,preprocessorwillinsertvalueof 3.1416insteadofstringPI doublevalue=2.1E 2 usingscientificnotation,2.1x10 ­2  scope  o Local accessiblewithinablockwhereitisdefined BlockinCisasubsectionofaprogrambetweenopenbracecharacter{and closingbracecharacter} o Global accessiblethroughouttheprogram o  Ifthevariableisdefinedoutsideofanyfunction,itisglobal Ifitisdeclaredinsidesomefunction,itislocaltothatfunctiononly TherearetwostorageclassesforvariablesinC o staticmodifiercanbeusedtomakethevariabletoretainitsvaluebetweencodeblock invocations o ifstaticisnotspecified,automaticstorageclassisassumed o automaticvariableslosetheirvalueswhentheblockinwhichtheyaredeclared terminates  6 V.Kindratenko ECE190 Lecture03 January25,2011 o globalvariablesareofstaticstorageclass Allocationofspaceforvariables o Whenacompiledprogramisloadedintocomputermemory,itsmemoryfootprintlooks likethis: Program text in binary Global data section Heap Run-time stack o o o  Globaldatasectioniswhereallvariablesofthestaticstorageclassareallocated Therun ­timestackiswherelocalvariables(oftheautomaticstorageclass)areallocated Everyfunctioninvocationhasarecordintherun ­timestack,calledactivation record,orstackframe Inordertoconstructthesememoryrecords,compilergeneratesasymboltable;this tableincludesnames,storageclass,andscopeinfoforallvariablesintheprogram Moreonthislaterinthecourse Operators, expressions and statements Expression:combinationofvariablesandliteralswithoperators,e.g., o x*y o 2+7 Statement:expressesacompleteunitofwork,includesassignmentoperator o Example:z=x*y; valueofxismultipliedbyvalueofyand theresultingvalueisassignedtovariablez here,x*yisanexpressionandz=x*yisastatement o semicolon(;)terminatesstatement o braces{}areusedtoformacompoundstatement,orblock,e.g., { a=b+c  i=p*q  } o Semicolonbyitselfindicatesanullstatement  o Example:z=x*y; Expressionx*yisevaluatedand  7 V.Kindratenko ECE190 Lecture03 o January25,2011 theresultingvalueisassignedtovariablez =istheassignmentoperator Thevalueontherightoftheassignmentoperatorwillbeassignedtothe variablewhosenameisprovidedontheleftsideoftheoperator Thevalueactuallywillbecopiedtothememoryassociatedwiththe variablenameontheleftoftheassignmentoperator Wewillstudytherestoftheoperatorsinthenextlecture Basic I/O with printf and scanf Outputviaprintf(printformatted)function o printffunctionperformsoutputtothestandardoutputdevice,typicallymonitor o requiresaformatstringthatdefines texttoprintout specificationsonhowtoprintoutvaluesofvariables o andvariableswhosevalueistobeprinted o examples  \  \  \  Inputviascanf(scanformatted)function o scanfperformsaninputfromthestandardinputdevice,typicallykeyboard o italsodoestypeconversionfromASCIItothetypespecifiedintheformatstring o examples    note&symbolinfrontofthevariablenames thissymbolisreferredtoasaddressoperator,moreonthislater someformatstringconventions o %d decimal o %i integer o %x hexadecimal o %c ASCIIcharacter o %s stringofASCIIcharacters o %f floatingpointvalue o \n newlinecharacter o 3   8 V.Kindratenko ...
View Full Document

Ask a homework question - tutors are online