Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I.

Similar presentations


Presentation on theme: "Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I."— Presentation transcript:

1

2 Functions Structured Programming 256 Chapter 6

3 Functions g prototypes g arguments g overloading g return values part I

4 Functions 1 are subprograms in C++. 1 perform a specific task. 1 can act on data and return a value. 1 Every C++ program has at least one function: main(). 1 are self-contained blocks of code, the inner workings of which are invisible to the remainder of the program.

5 Functions Why use functions? 1 make programs easier to write, debug and maintain - divide and conquer! Two main types of functions: 1 predefined -- found in the header files 1 user-defined -- today’s topic

6 Function - an example { int var1=1, var2=2, var3=3, var4=4; function1(“ASU”, var1); some statements; function2(var4, var3); function3(var2); }

7 Function - an example void function1(char name, int place) {cout << name << “ is #” << place << endl; } void function2(int al, int mel) {cout <<“var3 x var4 = “ << mel / al<<endl; } void function3(int casey) {cout << casey << “ is the value in var2\n”; }

8 Function properties 1 may be called 1 may be passed data called arguments 1 may return a value to the calling program 1 will not change the data stored in a received variable unless specifically instructed to do so

9 © 2000 Scott S Albert Functions 1. #include 2. void demofunction(void); 3. void main(void) 4. { 5. cout << "In main\n"; 6. demofunction(); 7. cout << "Back in main\n"; 8. } 9. void demofunction(void) 10. { 11. cout << "In DemoFunction\n"; 12. cout << “Still in function.\n”; 13. }

10 © 2000 Scott S Albert Function Output 5. In main 6. (calls function - 11. )In Demo Function - 12. ) Still in function. 7. Back in main Line # * *

11 Function declaration double Pythagorus( double, double );double Pythagorus( double, double ); data types onlydata types only

12 Function Syntax Syntax function header line function header { statements function body } *

13 Function Header Syntax Syntax typetype function_name(parameters) no ; Example double double Pythagorus(double a, double b)

14 ExampleExample double Pythagorus(double a, double b) Function Definition * no ; { type var { double c; c = sqrt(a*a + b*b); return return c; }

15 Function Call void main(void) { cout << “The hypotenuse is “ << Pythagorus(12, 5); } OUTPUT The hypotenuse is 13

16 Program Structure #include function prototypes; void main(void) { variable declarations; statements [including function calls] } function definition(s)

17 Function Prototypes Syntax return type function_name(type); Example double Pythagorus(double, double); *

18 Function Prototypes ExamplesExamples double Pythagorus(double, double); double Pythagorus(double, double); void do_stuff(void);void do_stuff(void); double times-em(int, int, int, int);double times-em(int, int, int, int); double myfunc(double, int);double myfunc(double, int); void print_em(char, double);void print_em(char, double);

19 Function Calls SyntaxSyntax function_name(arguments); ExampleExample Pythagorus(3.0, 4.0); *

20 Function Calls find_max(firstnum, secnum); get firstnum, find_max(, ) 865 get secnum * * * 865 865 firstnum 9090 secnummemory9090

21 Function Calls answer = Pythagorus(3.0,4.0); cout << “The hypotenuse = “ << answer << endl; * cout << “The hypotenuse = “ << Pythagorus(3.0,4.0)<<endl;

22 Function Calls answer = Pythagorus(3.0,4.0); answer answer * 100;answer = answer * 100; cout << “The hypotenuse = “ << answer << endl; * * 100 cout << “Hypotenuse = “ << Pythagorus(3.0,4.0) * 100 <<endl;

23 Program Structure #include function prototypes; void main(void) { variable declarations; statements [including function calls] } function definition(s)

24 Program Structure main function square call cube call square function cube function #include square prototype cube prototype

25 Program Structure int square(int);// function prototype int cube(int);// or function declaration void main(void) { int x = 8; square(x)cout <<“The square is “<< square(x) <<‘\n’; cube(x)cout <<“The cube is “ << cube(x) <<endl;... } int square(int n)// function definition {continued on next slide

26 Program Structure int square(int n)// function definition { int answer; answer = n*n; return answer; } int cube(int n) // function definition { int answer; answer = n*n*n; return answer; } { OR return n*n; { OR return n*n*n; *

27 Function Summary Prototype type function_name(parameter types) ; Call function_name(actual parameters) ; formal Definition formal type function_name(parameter types names) type function_name(parameter types & names) { } double Pythagorus(double, double); Pythagorus(height, base); double Pythagorus(double a, double b) * * * * *

28 Function Overloading Two or more distinct functions may have the same name. The data types of the arguments in the function calls must match those in the prototypes and in the definitions. The same function is given multiple definitions or implementations. The correct one is chosen by the compiler, not the programmer. * * *

29 Function Overloading The functions must differ in their parameter lists. The type and/or number of parameters must be different. Examples double myFunction(int, int, int); int myFunction(double, int, int); int myFunction (double, double); void myFunction(double); *

30 Function Overloading * *. // a is used // c is used // b is used // d is used myFunction(3,4,5); myFunction(3.0, 4.0); myFunction(11.1, 9, 2); myFunction(23.56); { callcall a double myFunction(int, int, int) b int myFunction(double, int, int) c int myFunction (double, double) d void myFunction(double) } Header

31 Returning Values A function can receive many valuesA function can receive many values Only one value can be directly returnedOnly one value can be directly returned

32 Returning Values returnThe return statement: 1 tells the function which value to send back to the calling program 1 terminates the function call and returns immediately to the calling program

33 Return Statement Syntax return expression; Examples return c; return hypotenuse;

34 Return Statement int find_max(int x, int y) { int maximum; if (x >= y) maximum = x; else maximum = y; return maximum; } same data type *

35 Passing Data 1 passing by value gives a single value 1p1passing by reference may give back several values accomplished by using references (this topic) using pointers *

36 double Pythagorus(double a, double b) { double c; c = sqrt(a*a + b*b); return c; } Passing Data - by Value copypassing by value: A copy of a value is passed from the calling function to the called function. * double Pythagorus(double a, double b) { a = a * a; b = b * b; double c = sqrt(a*a + b*b); return c; }

37 x find_max(x, y) arguments y * find_max(firstnum, secnum); call to find_max value in first_num is passed 865 value in sec_num is passed 9090 Storing Values into Parameters

38 void main(void)void main(void) {double height = 4.0, base = 3.0;{double height = 4.0, base = 3.0; double Pythagorus(double, double);double Pythagorus(double, double); cout << “Hypotenuse = “ << Pythagorus(height, base)<<endl;cout << “Hypotenuse = “ << Pythagorus(height, base)<<endl;...... } double Pythagorus(double a, double b)double Pythagorus(double a, double b) {double c; c = sqrt(a*a + b*b);{double c; c = sqrt(a*a + b*b); return c;return c; } Passing Data - by Value * 4.03.0

39 double Pythagorus(double a, double b) {double c; a++; b++; c = sqrt(a*a + b*b); return c; } Passing Data - by Value * back in main:cout << height; cout << base: 4.0 3.0

40 Passing Data - by Value void print_val(int); // function prototype void main(void) { int w = 3; cout <<"w before the function call is "<<w<<‘\n’; print_val(w); cout <<"w after the function call is "<<w<<‘\n’; } void print_val(int q) {cout<<"Value passed to the function is "<<q<<endl; q = q *2;// doubles the value cout<<"Value at the end of the function is "<< q <<endl; }

41 Passing Data - by Value Output w before the function call 3 Value passed to the function is 3 Value at the end of the function is 6 w after the function call is 3

42 Passing Data - by Reference Syntax && double Pythagorus(double &, double &); Pythagorus(height, base); & & double Pythagorus(double& a, double& b) function prototype function call function definition

43 void main(void) {double height = 4.0, base = 3.0; &&double Pythagorus(double &, double &); cout << “Hypotenuse = “ << Pythagorus(height, base) << endl;... } & &double Pythagorus(double& a, double& b) {double c; c = sqrt(a*a + b*b); return c; } Passing Data - by Reference * address of height address of base

44 & &double Pythagorus(double& a, double& b) {double c; a++; b++; c = sqrt(a*a + b*b); return c; } Passing Data - by Reference * address of height address of base back in main:cout << height; cout << base:

45 Passing Data - by Reference In main() values referenced as 1 value stored a height 1 value stored b base In Pythagorus() values referenced as *

46 Passing Data - by Reference { float a, b, c, sum, product; void calc(float, float, float, float &, float &); // prototype cout << "Enter three numbers: "; cin >> a >> b >> c; calc(a, b, c, sum, product); // call cout << a<<“ + “<<b<<“ + “c<<“ = " << sum; cout << ‘\n’<<a<<“ * “<<b<<“ * “c<<“ = " << product; } void calc(float x, float y, float z, float &tot, float& multiply) {tot = x + y + z; // definition multiply = x * y * z; x++; y++; z--;// for demo purposes }

47 Passing Data - by Reference Output Enter three numbers: 5 7 9 5 + 7 + 9 = 21 5 * 7 * 9 = 315 * x is 6, y is 8, z is 8 tot and sum refer to the same address product and multiply refer to the same address

48 Passing Data - by Reference void main(void) { int w = 3; void print_val(int &);// function prototype cout <<"w before the function call is "<<w<<‘\n’; print_val(w); cout <<"w after the function call is "<<w<<‘\n’; } void print_val(int& q) {cout<<"Value passed to the function is "<<q<<endl; q = q *2;// doubles the value cout<<"Value at the end of the function is "<< q <<endl; }

49 Passing Data - by Reference Output w before the function call 3 Value passed to the function is 3 Value at the end of the function is 6 w after the function call is 6

50 Swap Routine void swap(float& num1, float& num2) { float temp; temp = num1; num1 = num2; num2 = temp; }

51 Data Type Mismatch value parameters implicit type conversion - value of the actual parameter is coerced to the data type of the formal parameter reference parameters no coercion because an address is passed, not a value *

52 A Comparison formalactual parameter isparameter may be valuevariable, constant, or expression type coercion may take place referencevariable only of exact same type as formal

53 What’s Happening???? call sequence 1. memory is allocated 2. parameters are passed 3. transfer of control return sequence 1. value of the return is stored 2. memory is deallocated 3. transfer of control *

54 Functions g g Data Flow g Scope local global part II g Global Resolution Operator part II

55 Data Flow Data flow is the direction of the information flow between the function and its caller. Adding data flow documentation to the function interface is helpful. The flow could be into a function, out of a function or both.

56 Parameter and Data Flow /* in */ 4 pass data into a function/* in */ /* out */ 4 pass data out of a function/* out */ /* inout */ 4 pass data into and out of a function/* inout */

57 Examples void myFunction( /* in */ double nana, /* in */ int count) void yourFunction( /* out */ int& num1, /* out */ int& num2) void ourFunction( /* in */ int alpha, /* inout */ int& beta) Parameter and Data Flow

58 , To be certain a function does what you want it to do, write value of variables as you enter and exit a function., Put the output statement into a function and call it whenever you need it. void ShowIt(void) { cout<< var1<< ‘\t’ <<var2<< ‘\t’ <<var3<< ‘\n’; } *

59 Parameter and Data Flow Flow In int media( /* in */ int cow) { cout << “Ten * cow = “ << cow*10; return (2*cow +5); } int media( /* in */ int cow) { cow = 2 * cow; return (2*cow +5); } & out & *

60 Parameter and Data Flow Flow Out void media( /* out */ float& delta, /* out */ float& epsilon ) { delta = 1.0; epsilon = 0.0002; } epsilon = epsilon - 0.0001; * inout inout epsilon = epsilon - 0.0001; epsilon = epsilon - 0.0001;

61 Parameter and Data Flow Flow In and Out void update( /* inout */ int& javel, /* inout */ int & grenelle ) { javel = 3 * javel; grenelle++; }

62 Data Flow - Example #include void getTemp(double&); void activity(double); void convertCtoF(double&); void main(void) { double temperature; getTemp(temperature); activity(temperature); }

63 Data Flow - Example void getTemp(/* */ double& temp) { cout<<"Enter the temperature in degrees C: "; cin>> temp; cout<<"The current temperature is " <<temp<<" degrees celsius."<<endl; convertCtoF(temp); } void convertCtoF( /* */ double& temp) { temp=(1.8)*temp +32; cout<<"This equals "<<temp <<" degrees Fahrenheit."<<endl; } out inout *

64 Data Flow - Example void activity(/* */ double temp) { cout<<"The recommended activity is "; if(temp>85) cout<<"swimming."<<endl; else if(temp>70) cout<<"tennis."<<endl; else if(temp>35) cout<<"golf."<<endl; else if(temp>10) cout<<"skiing."<<endl; else cout<<"dancing."<<endl; } in *

65 Data Flow data flowparameter-passing for a parametermechanismdata flowparameter-passing for a parametermechanism incomingpass-by-value outgoingpass-by-reference incoming/outgoingpass-by-reference

66 I/O Example void main(void) { 1 int red, blue; 2 void Mix( int&, int ); // prototype 3 int Blend( int, int ); // prototype 4 red = 5; 5 blue = Blend(3, red + 1); 6 Mix(red, blue); 7 cout << red << ' ' << blue << '\n'; 8 Mix(red, blue + red); 9 cout << red << ' ' << blue << '\n'; 10 Mix(red, Blend(blue, red)); 11 cout << red << ' ' << blue << '\n'; }

67 I/O Example M void Mix( int& green, int yellow) { M1 int purple; M2 cout << “enter Mix “ << green << ‘ ‘ << yellow << ‘\n’; M3 purple = green + yellow; M4 yellow = purple + yellow; M5 green = purple; M6 cout << “leav Mix “ << green << ‘ ‘ << yellow << ‘\n’; }

68 I/O Example B int Blend( int red, int green ) { B1 int yellow; B2 cout << “enter Blend “ << red <<‘ ‘ << green << ‘\n’; B3 yellow = red + green; B4 cout << “leave Blend “ << red <<‘ ‘ << green << ‘\n’; B5 return (yellow + 1); }

69 void Mix( /* ______ */ int& green, /* ______ */ int yellow ) int Blend( /* ______ */ int red, /* ______ */ int green ) I/O Example inout in * *

70 1 2 3 4 5 B B1 - B5 6 M M1 - M6 I/O Example * * 7 8 M M1 - M6 9 10 M B B1 - B5 M1 - M6 11 The lines are executed in this order.

71 I/O Example MixmemoryMain greenred blue yellow purplepurple

72 © 2000 Scott S Albert Mix Blend Main enter Blend 3 6 leave Blend 3 6 enter Mix 5 10 leave Mix 15 25 15 10 enter Mix 15 25 leave Mix 40 65 40 10 enter Blend 10 40 leave Blend 10 40 enter Mix 40 51 leave Mix 91 142 91 10 *

73 Scope A function is like a black box: You know what goes in and what comes out, but you do not know what happens inside the box.

74 Scope The section of the program where the variable is valid (known or visible). local = available to only one function global = available several functions

75 Scope blockLocal: The scope of an identifier declared inside a block extends from the point of declaration to the end of that block. Global: The scope of an identifier declared outside all functions and classes extends from the point of declaration to the end of the source file. *

76 Local Variables / declared within a function definition / private to a function definition / variables in different functions are totally independent / different functions can have variables with the same names; however, each variable will have its own memory address * *

77 int x = 3;int x = 3;// global because before main void main(void) {// no variables local to main( ) void myfunction( );// prototype cout <<"x = "<<x<<" before the function call.\n"; myfunction( ); cout <<"x = "<<x<<" after the function call.\n"; } void myfunction( ) { int r;// local to myfunction( ) r = ++x; cout <<"r = "<<r<<" within the function.\n"; }

78 Scope OUTPUT x = 3 before the function call. r = 4 within the function. x = 4 after the function call.

79 Example - ReadValues void main(void) { int a, b, c; float avg; void ReadValues( int&, int&, int& ); void Adjust( int&, int&, int& ); float Average( int, int, int ); void WriteResults( int, int, int, int, float ); ReadValues(a, b, c); Adjust(a, b, c); avg = Average(a, b, c); WriteResults(a, b, c, a + b + c, avg); } 1. 2. 3. 4. 5. 6. 7. 8. 9.

80 Example - ReadValues 1.main declares and calls ReadValues 2.ReadValues declares and calls ReadOne [3x] 3.main declares and calls Adjust 4.main declares and calls Average 5.main declares and calls WriteResults * *

81 Example - ReadValues void ReadValues( /* */ int& x, /* */ int& y, /* */ int& z ) { void ReadOne( char, int& ); ReadOne('1', x ); ReadOne('2', y ); ReadOne('3', z ); return; } * out

82 Example - ReadOne void ReadOne( /* */ char number, /* */ int& item ) { cout << "Enter value " << number << ": "; cin >> item; return; } * in out

83 Example - Adjust void Adjust( /* */ int& i, /* */ int& j, /* */ int& k ) { int smallest; smallest = i; if (j < smallest) i = i - smallest; smallest = j; j = j - smallest; if (k < smallest) k = k - smallest; smallest = k; return; } * inout

84 Example - Average float Average( /* */ int item1, /* */ int item2, /* */ int item3 ) { int total; total = item1 + item2 + item3; return float(total) / 3; } * in

85 Example - WriteResults void WriteResults( /* */ int item1, /* */ int item2, /* */ int item3, /* */ int total, /* */ float average ) { cout << "Adjusted values: " << item1 << ", " << item2 << ", " << item3 << '\n' << "Sum: " << total << " Average: " << average << '\n'; return; } * in

86 © 2000 Scott S Albert ReadValuesAdjustAverageWriteResults ReadOne Main Enter value 1: 23 Enter value 2: 56 Enter value 3: 78 Adjusted values: 0, 33, 55 Sum: 88 Average: 29.3333

87 globalvoid swap(int, int);// a global function void main(void) {int x = 5, y = 10; 1.cout <<“Main-before swap, x: “<<x<<" y: "<<y<< '\n'; swap(x, y); 2. cout <<"Main-after swap, x: "<<x<<" y: "<<y<<'\n'; } void swap(int x, int y) {int temp; 3. cout <<"Swap-before swap, x: "<<x<<" y: "<<y<<'\n'; temp = x;x = y;y = temp; 4. cout <<"Swap-after swap, x: "<<x<<" y: "<<y<<'\n'; }

88 Scope OUTPUT 1. Main-before swap:x: 5y: 10 3. Swap-before swap:x: 5 y: 10 10 5 4. Swap-after swap:x: 10 y: 5 2. Main-after swap:x: 5 y: 10

89 void Block1(int, char &); void Block2( ); int a1;// global char a2; // global int main() {... } Scope within a Block slide 1 of 2

90 void Block1(int a1, char &b2) // prevents access { // to global a1 int c1;// local to Block1 int d1; // local to Block1 } } slide 2 of 2 slide 2 of 2 *... void Block2() { int a1;// prevents access to global a1 int b1;// local to Block2 while (…) // Block3 { // Block3 int c1;// local to Block3 int b2;// prevents non-local access } }// to b2 in Block1...

91 Scope within a block - Ex. 1 predict the output void scope2(void);// function prototype void main(void) int v=100;{int v=100; cout <<"v BEFORE function = "<<v<<'\n'; scope2(); cout <<"v AFTER function = "<<v<<'\n'; } slide 1 of 2

92 Scope within a block - Ex. 1 predict the output 1. void scope2(void) //function header 2. {double v = 5.5; 3. int k, j; 4. cout << "v outside block = " << v<<'\n'; 5. for (k=1; k<=3; k++) 6. { int v = 17; // initialized in function 7. for (j=1; j<=2; j++) 8. {v++; 9. cout << "v inside block = " << v<<'\n'; 10. } 11. } 12. cout << "v outside block = " << v<<'\n'; 13. } slide 2 of 2

93 Scope within a block - Ex. 2 void scope2(void);// function prototype void main(void) int v=100;{int v=100; cout <<"v BEFORE function = "<<v<<'\n'; scope2(); cout <<"v AFTER function = "<<v<<'\n'; } slide 1 of 2

94 Scope within a block - Ex. 2 slide 2 of 2 1. void scope2(void) //function header 2. { double v = 5.5; 3. int k, j; 4. cout << "v outside block = " << v <<'\n'; 5. for (k=1; k<=3; k++) int v = 17 6. { int v = 17; // initialized in function 7. for (j=1; j<=2; j++) v 8. { v ++; v 9. cout << "v inside block = " << v <<'\n'; 10. } 11. } 12. cout << "v outside block = " << v <<'\n'; }

95 Scope within a block OUTPUT 100 BEFORE 5.5 outside 18inside18inside 19inside19inside 18inside18inside 19inside19inside 18inside18inside 19inside19inside 5.5 outside 100 AFTER j loops } } } *

96 Global Resolution Operator :: :: double rougon = 999.99;// global void main(void) { double rougon = 12.3;// local cout<< rougon << “ = rougon, local\n” cout<< ::rougon << “ = rougon, global\n”; } OUTPUTOUTPUT 12.3 = rougon, local 999.99 = rougon, global *

97 Variable Storage Classes Local auto static register  while (  ) {int k = 1; k++;  } * * * while (  ) {static int k = 1; k++;  }

98 Global static extern  Variable Storage Classes

99 Scope & Storage Classes - an example int x = 1; // global variable main() { int x = 5; // local variable to main cout << "local x in outer scope of main is " << x << endl; { // start new scope int x = 7; cout << "local x in inner scope of main is " <<x<< endl; } // end new scope cout << "local x in outer scope of main is " << x << endl;

100 Scope & Storage Classes - an example (continued) a(); // a has automatic local x b(); // b has static local x c(); // c uses global x a(); // a reinitializes automatic local x b(); // static local x retains its previous value c(); // global x also retains its value cout << "local x in main is " << x << endl; return 0; }// end of main()

101 Scope & Storage Classes - an example void a(void) { int x = 25; // initialized each time a is called cout << endl << "local x in a is " << x << " after entering a" << endl; ++x; cout << "local x in a is " << x << " before exiting a" << endl; }

102 Scope & Storage Classes - an example void b(void) { static int x = 50; // Static initialization only // first time b is called cout << endl << "local static x is " << x << " on entering b" << endl; ++x; cout << "local static x is " << x << " on exiting b" << endl; }

103 Scope & Storage Classes - an example void c(void) { cout << endl << "global x is " << x << " on entering c" << endl; x *= 10; cout << "global x is " << x << " on exiting c" << endl; }

104 Scope & Storage Classes - an example a(); // a has automatic local x b(); // b has static local x c(); // c uses global x a(); // a reinitializes automatic local x b(); // static local x retains its previous value c(); // global x also retains its value a(); b(); c(); *

105 Scope & Storage Classes - an example OUTPUT local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c

106 Scope & Storage Classes - an example local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5

107 Scope & Storage Classes - an example void a(void) { int x = 25; // initialized each time a is called cout << endl << "local x in a is " << x << " after entering a" << endl; ++x; cout << "local x in a is " << x << " before exiting a" << endl; } << ‘\t’ << ::x << ‘\t’ << ::x << endl; *

108 © 2000 Scott S Albert Common Errors 4 Passing incorrect data types 4 Using the same variable name for different variables ex. local - in both the calling and called functions global - must use ::

109 © 2000 Scott S Albert Common Errors 4 Wrong positioning of the called function prototype 4 Terminating a function header with a ; 4 Forgetting the data type of a function’s parameter


Download ppt "Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I."

Similar presentations


Ads by Google