Electrical Engineering - Chapter 7: Functions

Code group that performs single task Specification refers to what goes into and out of function Design refers to function’s task(s) Two groups Library Programmer-defined

ppt30 trang | Chia sẻ: thuongdt324 | Lượt xem: 461 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Electrical Engineering - Chapter 7: Functions, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Chapter 7 - FunctionsFunctionsCode group that performs single taskSpecification refers to what goes into and out of functionDesign refers to function’s task(s)Two groupsLibraryProgrammer-definedLesson 7.1Function CategoriesReturn no valueReturn a single valueUse “pass by reference”Lesson 7.1Function BasicsNeed three things to use functionFunction declaration (prototype)Indicates function exists and describes itMust be done before use of functionFunction call (invocation)Causes control to transfer from function to functionFunction definitionHeader line followed by function body enclosed in bracesLesson 7.1Function DeclarationIndicates function name, return type and types of values passed to functionGeneral form ftype fname (atype, atype);ftype is function return typefname is function nameatype is argument type (may be different)multiple argument separated by commasLesson 7.1Function CallTransfers program control to functionGeneral form fname (exp1, exp2);fname is function nameexp1 and exp2 are argumentsVariables or constantsCalled argument listLesson 7.1Function DefinitionIncludes function’s executable statementsGeneral form (example with two arguments) Lesson 7.1Function return typeFunction return typeFunction argument declarationsFunction bodyftype fname (atype aname, atype aname) { }Argument ListsLists in function call and function header must coordinatenumberordertypeExample:Lesson 7.1kinetic_energy (mass, velocity);void kinetic_energy (int m, double v)Function call in mainFunction header2 arguments in eachmass should be declared an integer and velocity a double in programFunction ArrangementNot necessary for first function to be mainFunction definition must be located outside body of any other functionCan write function declaration outside body of all functions or within functionif within, can only be called from function where declaredFunction declaration MUST appear before callLesson 7.1Function StorageWhen function called, memory allocated forVariables in argument listVariables declared in function bodyWhen completes execution, memory freed and variable values lostCan prevent lost and maintainCalled multiple times, allocated and freed repeatedlyLesson 7.1Common ErrorsArgument order not matching between function call and headerMismatching data typesPass more information than function needs to complete taskLesson 7.1Returning a ValueTwo items neededappropriate return type for functionreturn statement in functionFunction declaration and definition list return data type int fact(double); int fact(double arg)return statement form return expression;Lesson 7.2Can put expression in ( ).Return StatementConsidered to be jump statementCan appear anywhere in function bodyMore than one return statement can appear in functionLesson 7.2if (expression) { return (a); }else { return (b); }Returning Value From mainvoid type function do not return valuescontrol transfers back to calling function automatically int main ( ) return (0);Returns value 0 to operating system indicating normal terminationLesson 7.2Recap: Pass By ValueDefaultFunction calledMemory set aside and value copied into new memory locationCalculations done inside function using valueWhen function finished executing, memory location destroyedLesson 7.2Pass By ReferenceUse argument list to allow function to directly use calling function's valuesReference symbol & required in function declaration and headerIndicate arguments that will have values modifiedCreate aliases for original variable namesLesson 7.3Pass By ReferenceExample:Lesson 7.3void func_name (int, double, double&, int&);func_name (x, y , z, a);void func_name ( int b, double c, double& d, int& e)DeclarationCallHeaderx y z ab cd eScopeRefers to region in which declaration is activeThree kinds of scopeBlockVariable valid with block of code enclosed in bracesFunctionVariable valid only within function where definedFileVariable valid throughout all modules in fileDetermined by identifier's declaration locationLesson 7.4ScopeLesson 7.4File containing functions main ( ) and calc ( )int days;Function calc ( ) int y;for (int n=0;n<8;n++) { }Function main ( ) int x;for (int j=0;j<8;j++) { }daysdaysdaysdaysdaysxxyynjStorage ClassesAllows manual modification to scope and storage rulesStated in the declarationFour specifiersregister : store in registerauto : memory freed after function executesstatic : memory persists after function executesextern : global variables among filesLesson 7.5staticVariable maintains storage space and value after function finishes executingMemory reserved and initialized only onceFirst time function calledGeneral form: static type variable;Can be initialized in declarationDone once, does not initialize on other callsLesson 7.5Comparing global and static VariablesSimilarityPermanent storage created for bothDifferenceScopeStatic variables accessed only from function in which declaredGlobal variables accessed from any functionWith extern from any fileLesson 7.5externMultiple files help manage large programsEach compiled separately then linked to create executable fileShare variableVariable declared as global without specifier in one fileOther files extern type variable;Lesson 7.5Default ArgumentsArgument assigned particular value when argument omitted in function callValues specified in function declarationMust have ordinary argument listed prior to default argumentsLesson 7.6type function_name ( ordinary arguments, default arguments);Using Default ArgumentsCalling functionMust be called with at least the number of ordinary argumentsvoid commute (double, double = 15.0, int = 8);commute ( 40.0 );Call uses 40.0 for first argument, then default values: 15.0 for second argument and 8 for thirdCannot specify first and third and use default for second – must have all defaults last!Lesson 7.6Function OverloadingDefining two or more functions with same nameEach function takes different number of argumentsC++ knows which function is being called by counting number of arguments usedShould not use default arguments since ambiguity could resultLesson 7.7Generating Random NumbersNeed three functionsrand ( )Returns pseudorandom integer in range 0 to 32767srand ( )Operates with rand( ) using global variable invisible to programmertime ( )Returns number of seconds from midnightNeed mod (%) operator to restrict rangeLesson 7.8Generating a Random Numberrand( ) and srand ( ) work togethersrand ( ) automatically "seeds" function rand ( ) Functions linked through global variabletime ( ) used to get true random effectsrand (time (0));rand ( )returns single integer time of day in secondsCall to create random numberLesson 7.8Random Number in Specific RangeUse mod operatorExample: n = rand ( ); roll = (n % 6) + 1;Simulate roll of die so result should be integer from 1 to 6Lesson 7.8SummaryDefine and call functionsDetermine the scope of a variablePass values by referenceOverload functionsCreate random numbersChapter 7Learned how to:
Tài liệu liên quan