Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide and Conquer technique Allow programs to be broken down into smaller pieces. This makes programs easier to read and maintain. Statements in function bodies are written only once Reused from perhaps several locations in a program Hidden from other functions Avoid repeating code Spring 2016 CISC1600 Yanjun Li 2 1
Functions Functions you have used: main() starting point of a program, calls other functions Other function: std::setprecision( x ) Spring 2016 CISC1600 Yanjun Li 3 Define A Function Definition of a method: Header : Return type, Function Name, Parameter(s) [ type and name pair ]. Body : a collection of statements. Example: int addtwonumbers (int numberone, int numbertwo ) { int sum; sum = numberone + numbertwo; } return sum; Spring 2016 CISC1600 Yanjun Li 4 2
Function Prototype Also called a function declaration Indicates to the compiler: Type of data returned by the function Function Signature Name of the function Parameters the function expects to receive Number of parameters Types of those parameters Order of those parameters Example: int addtwonumbers(int, int); Function prototype is provided before the function is invoked. Spring 2016 CISC1600 Yanjun Li 5 User A Function Invoked with function name and parameters Example: int x, y, sum; x = 4; y = 5; //invoke funtion addtwonumbers to do the addition sum = addtwonumbers(x, y); Spring 2016 CISC1600 Yanjun Li 6 3
Another Example Define the Function : void displaymessage (int number) { cout<< "The result is "<< number <<endl; } Invoke the Function : displaymessage ( sum ); Output : The result is 9 Spring 2016 CISC1600 Yanjun Li 7 One More Example Define the Function : void displaywelcomemessage ( ) { cout<< Welcome to The World of C++! "<<endl; } Invoke the Function : displaywelcomemessage ( ); Output : Welcome to The World of C++! Spring 2016 CISC1600 Yanjun Li 8 4
How Function Call Works (1) Spring 2016 CISC1600 Yanjun Li 9 How Function Call Works (2) Spring 2016 CISC1600 Yanjun Li 10 5
How Function Call Works (3) Spring 2016 CISC1600 Yanjun Li 11 Math Library Functions Have function prototypes placed in header files Can be reused in any program that includes the header file and that can link to the function s object code Example: sqrt in <cmath> header file sqrt( 900.0 ) Spring 2016 CISC1600 Yanjun Li 12 6
Useful Standard Library Function Standard library function std::pow( ) Calculates an exponent Function takes two arguments of type double and returns a double value. Requires header file <cmath> Example : #include <cmath> using std::pow; //in main function double x,y,result; x=2; y=2; result = pow(x,y); Calculates the value of x raised to the y th power Spring 2016 CISC1600 Yanjun Li 13 Function Description Example ceil( x ) cos( x ) rounds x to the smallest integer not less than x trigonometric cosine of x (x in radians) ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( 0.0 ) is 1.0 exp( x ) exponential function e x exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76 floor( x ) fmod( x, y ) log( x ) rounds x to the largest integer not greater than x remainder of x/y as a floating-point number natural logarithm of x (base e) floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 fmod( 2.6, 1.2 ) is 0.2 log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( x, y ) x raised to power y (x y ) pow( 2, 7 ) is 128 pow( 9,.5 ) is 3 sin( x ) sqrt( x ) tan( x ) trigonometric sine of x (x in radians) square root of x (where x is a nonnegative value) trigonometric tangent of x (x in radians) sin( 0.0 ) is 0 sqrt( 9.0 ) is 3.0 tan( 0.0 ) is 0 Fig. 6.2 Math library functions Spring 2016 CISC1600 Yanjun Li 14 7
Default Arguments A default value to be passed to a parameter Used when the function call does not specify an argument for that parameter Must be the rightmost argument(s) in a function s parameter list Should be specified with the first occurrence of the function name Typically the function prototype It is a compilation error to specify default arguments in both a function s prototype and header. Spring 2016 CISC1600 Yanjun Li 15 1 // Fig. 6.22: fig06_22.cpp 2 // Using default arguments. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 // function prototype that specifies default arguments 8 int boxvolume( int length = 1, int width = 1, int height = 1 ); 9 10 int main() 11 { 12 // no arguments--use default values for all dimensions 13 cout << "The default box volume is: " << boxvolume(); 14 15 // specify length; default width and height 16 cout << "\n\nthe volume of a box with length 10,\n" 17 << "width 1 and height 1 is: " << boxvolume( 10 ); 18 19 // specify length and width; default height 20 cout << "\n\nthe volume of a box with length 10,\n" 21 << "width 5 and height 1 is: " << boxvolume( 10, 5 ); 22 23 // specify all arguments 24 cout << "\n\nthe volume of a box with length 10,\n" 25 << "width 5 and height 2 is: " << boxvolume( 10, 5, 2 ) 26 << endl; 27 return 0; // indicates successful termination 28 } // end main Default arguments Calling function with no arguments Calling function with one argument Calling function with two arguments Calling function with three arguments Spring 2016 CISC1600 Yanjun Li 16 8
29 30 // function boxvolume calculates the volume of a box 31 int boxvolume( int length, int width, int height ) 32 { 33 return length * width * height; 34 } // end function boxvolume The default box volume is: 1 The volume of a box with length 10, width 1 and height 1 is: 10 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 Note that default arguments were specified in the function prototype, so they are not specified in the function header Spring 2016 CISC1600 Yanjun Li 17 Local Variable in Function The variables defined local to the block of the function would be accessible only within the block of the function and not outside the function. Example: int functionone(int x,int y) { int z; z=x+y; return z; } Spring 2016 CISC1600 Yanjun Li 18 9
Global Variables Created by placing variable declarations outside any function definition Retain their values throughout the execution of the program Can be referenced by any function that follows their declarations or definitions in the source file Spring 2016 CISC1600 Yanjun Li 19 Scope Rules (1) Scope Portion of the program where an identifier can be used We discuss two scopes for an identifier File scope Block scope Spring 2016 CISC1600 Yanjun Li 20 10
Scope Rules (2) File scope For an identifier declared outside any function Such an identifier is known in all functions from the point at which it is declared until the end of the file Global variables, function definitions and function prototypes placed outside a function all have file scope Spring 2016 CISC1600 Yanjun Li 21 Scope Rules (3) Functions in the same scope (File Scope) must have unique signatures The scope of a function is the region of a program in which the function is known and accessible It is a compilation error if two functions in the same scope have the same signature but different return types. Spring 2016 CISC1600 Yanjun Li 22 11
Scope Rules (4) Block scope Identifiers declared inside a block have block scope Block scope begins at the identifier s declaration Block scope ends at the terminating right brace (}) of the block in which the identifier is declared Local variables and function parameters have block scope The function body is their block Any block can contain variable declarations Spring 2016 CISC1600 Yanjun Li 23 Scope Rules (5) Block scope Identifiers in an outer block can be hidden when a nested block has a local identifier with the same name Example: int x= 10; for (int i=0; i<10; i++) { int x = 5+ i; } Spring 2016 CISC1600 Yanjun Li 24 12
References and Reference Parameters (1) Two ways to pass arguments to functions Pass-by-value A copy of the argument s value is passed to the called function Changes to the copy do not affect the original variable s value in the caller Prevents accidental side effects of functions Pass-by-reference Gives called function the ability to access and modify the caller s argument data directly Spring 2016 CISC1600 Yanjun Li 25 References and Reference Parameters (2) Reference Parameter An alias for its corresponding argument in a function call & placed after the parameter type in the function prototype and function header Example int funcname(int &count) in a function header Pronounced as count is a reference to an int Spring 2016 CISC1600 Yanjun Li 26 13
References and Reference Parameters (3) Parameter name in the body of the called function actually refers to the original variable in the calling function When the function is invoked, simply mention the variable by name to pass it by reference. Example int x, y; y = funcname(x); Spring 2016 CISC1600 Yanjun Li 27 Reference Reproduced from the Cyber Classroom for C++, How to Program, 5/e by Deitel & Deitel. Reproduced by permission of Pearson Education, Inc. Spring 2016 CISC1600 Yanjun Li 28 14