Functions Functions are defined as follows: return-value-type function-name( parameter-list ) { local declarations and statements Example: int square( int y ) { return y * y; 1 Function Prototypes Function prototype is needed if the function call comes before the function definition in the program. Function prototype consists of Return type (default int) Function name Parameters 3 1 // Fig. 3.3: fig03_03.cpp 2 // Creating and using a programmer-defined function 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 int square( int ); // function prototype 10 int main() 11 { 12 for ( int x = 1; x <= 10; x++ ) 13 cout << square( x ) << " "; 1 15 cout << endl; 16 return 0; 1 18 1 // Function definition 20 int square( int y ) 21 { 22 return y * y; 23 1 16 25 36 6 81 100 2 Functions with Empty Parameter Lists Empty parameter lists Either writing void or leaving a parameter list empty indicates that the function takes no arguments void print(); or void print( void ); Function print takes no arguments and returns no value 1
1 // Fig. 3.18: fig03_18.cpp 2 // Functions that take no arguments 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 void function1(); void function2( void ); 10 11 int main() 12 { 13 function1(); 1 function2(); 15 16 return 0; 1 18 1 void function1() 20 { 21 cout << "function1 takes no arguments" << endl; 22 23 2 void function2( void ) 25 { 26 cout << "function2 also takes no arguments" << endl; 2 function1 takes no arguments function2 also takes no arguments 5 1 // Fig. 3.23: fig03_23.cpp 2 // Using default arguments 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 int boxvolume( int length = 1, int width = 1, int height = 1 ); 10 int main() 11 { 12 cout << "The default box volume is: " << boxvolume() 13 << "\n\nthe volume of a box with length 10,\n" 1 << "width 1 and height 1 is: " << boxvolume( 10 ) 15 << "\n\nthe volume of a box with length 10,\n" 16 << "width 5 and height 1 is: " << boxvolume( 10, 5 ) 1 << "\n\nthe volume of a box with length 10,\n" 18 << "width 5 and height 2 is: " << boxvolume( 10, 5, 2 ) 1 << endl; 20 21 return 0; 22 23 2 // Calculate the volume of a box 25 int boxvolume( int length, int width, int height ) 26 { 2 return length * width * height; 28 Default Arguments The default box volume is: 1 The volume of a box with length 10, width 1 and height 1 is: 10 If function parameter is omitted, it gets a default value Rightmost parameters go to their defaults Defaults are set in function prototypes Example: The volume of a box with length 10, width 5 and height 1 is: 50 The volume of a box with length 10, width 5 and height 2 is: 100 Notice how the rightmost values are defaulted. int function( int x = 1, int y = 2, int z = 3 ); 6 8 2
Function Overloading Function overloading Having functions with same name and different parameters int square( int x) {return x * x; float square(float x) { return x * x; Program chooses function by signature signature determined by function name and parameter types Summary of C++ Functions What are they? Functions are subprograms that return a value given some arguments. The square root function, sqrt(argument), is an example of a function. C++ provides access to many standard functions via the #include directive. You have the capability to write your own functions. 11 1 // Fig. 3.25: fig03_25.cpp 2 // Using overloaded functions 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 int square( int x ) { return x * x; 10 double square( double y ) { return y * y; 11 12 int main() 13 { 1 cout << "The square of integer is " << square( ) 15 << "\nthe square of double.5 is " << square(.5 ) 16 << endl; 1 18 return 0; 1 The square of integer is The square of double.5 is 56.25 10 Summary of C++ Functions How do you implement your own functions? First, place a function prototype at the beginning of your program, before main(). Syntax: return_type fun_name(arg_type arg_name[,]); Examples: long AddAbsolute(int a, int b); double CubeRoot(double); void Display_Menu(void); 12 3
Summary of C++ Functions Then place the function implementation after the closing brace of main(){. Syntax: return_type fun_name(arg_type arg_name[,]){ function_body Example: int main(){ long AddAbsolute(int a, int b){ Summary of C++ Functions Functions with a return_type other than void should have a return statement. To call a function, place the function reference in an expression of the calling module, e.g. x = CubeRoot(a+b) + AddAbsolute(c,d); Do not output a function that has a return_type of void. Example: void printmenu(void); cout<< printmenu(); // DO NOT DO!! 13 15 Example #include <iostream> using namespace std; //Function Prototypes long AddAbsolute(int a, int b); double CubeRoot(double); //Main Function int main(){ //Function Implementations long AddAbsolute(int a, int b){ double CubeRoot(double x){ Summary of C++ Functions Do not use a function that has a return_type of void in a mathematical operation. Example: void printmenu(void); int x = printmenu(); // DO NOT DO!! See the examples of function implementations on the next page. 1 16
Function Example 1 Objective : Returns the maximum of a and b Prototype : int MaxVal( int, int ); int MaxVal(int a, int b) { if(a>b) return a; else return b; Function Example 3 Objective : Returns true if the input is an odd # Prototype : bool Odd( int ); bool Odd(int n) { if ((n % 2) == 1) return true; else return false; 1 1 Function Example 2 Objective : Returns true if the input is a prime # Prototype : bool isprime( int ); bool isprime( int n ) { bool prime = true; for (int i=2; i<=n-1; i++) { if (n%i == 0) prime = false; return prime; Notes about Functions Every function must have a name, using the same naming rules as variables. To differentiate functions from variables you may want to capitalize function names. Example: cube_root = Cube_Root(alpha); Functions may have zero or more arguments; parentheses are always required. Use the return statement to return a value from a function. Several alternative return statements are allowed, but only one return is suggested. 18 20 5
Notes about Functions A function with a return type of void returns nothing. A return statement is not needed. Use voided functions to perform tasks, like get_data, solve_problem or display_results. Typically, voided functions are called with a simple expression statement Function Example The complete implementation of a function may replace its prototype. This practice is generally discouraged. Objective : Returns true if the input is an odd # Prototype and #include <iostream> using namespace std; bool Odd ( int n ) { return n%2; Example: get_data(x,y,z); 21 int main(){ 23 Notes about Functions Function Example 5 Never define a function in another function. main() is a function. If you do not specify a return type, int is assumed. For clarity, make functions small, not more than one screen. Objective : Returns random numbers between 0 and 1 Prototype : double Random( unsigned long ); double Random(unsigned long seed){ seed = 238285 * seed; return double(seed) / 2625.0; 22 2 6
Function Example 6 Objective : Displays the menu Prototype : void Display_Menu( void ); void Display_Menu(void) { cout << endl << MAIN MENU << endl; cout << 0 - quit << endl; cout << 1 - Read a file << endl; cout << 2 - Print a record << endl; Function Example 8 Objective : Returns n!/(n-r)! Prototype : int Permutation( int, int ); int Permutation(int n, int r) { int perm = 1; for (int i=n-r+1; i<=n; i++) perm *= i; return perm; 25 2 Function Example Objective : Computes the area of a triangle given 2 sides and an angle Prototype : double SSA( double, float, double angle ); #define M_PI 3.11526535832386 double SSA(double s1, float s2, double angle) { const double RPD = M_PI/180.0; // radians/degree return 0.5 * s1 * s2 * sin(angle * RPD); Function Example 8 Objective : Returns n!/(n-r)! Prototype : int Permutation( int, int ); int Permutation(int n, int r) { return nfact(n)/nfact(n-r); 26 28
Function Example Objective : Returns n! / (r!(n-r)!) Prototype : int Combination( int, int ); int Combination(int n, int r) { int comb = Permutation(n,r); for (int i=1; i<=r; i++) comb /= i; return comb; Function Arguments float demo1(float x); passes x by value that is, changes to x in demo1 will not be seen by the calling program. Demo call: a = demo1(b+c); a = demo1(x); 2 31 Function Example Objective : Returns n! / (r!(n-r)!) Prototype : int Combination( int, int ); int Combination(int n, int r) { return nfact(n)/(nfact(r)*nfact(n-r)); Function Arguments Each argument must be individually typed, e.g., int f1(int a, int b);// correct int f2(int a, b); // incorrect Demo call: e = f1(f, g+h); Functions can have default argument values. int demo6(int n=0, int m=1); which means demo6(2) is the same as demo6(2,1) and demo6() is the same as demo6(0,1). 30 32 8
Function Arguments More than one function can have the same name (but different types of arguments). This is called function overloading. double cube(double x); long cube(long x); In this example, cube(2.5) will call the first function and cube() will call the second. C++ compares the type of value passed to a function and if different than the expected type, converts the argument to the correct type (if possible) 33