2
Functions
• A program can be thought of as a collection of sub parts or sub tasks:
• input data• analyze data• output results
• In C++ these sub tasks are often organized into functions.
3
Functions
• Complex problems can be broken down into sub tasks, each of which is easy to implement in C++.
• What are some other advantages to using functions, as opposed to writing the entire solution in main?
–Multiple programmers
–Testing/Debugging/Maintaining
–Reduce duplication of code
5
Pre-defined Functions - Example
#include <iostream>#include <cmath>using namespace std;int main(){ double angle; cout << “input angle in radians: “; cin >> angle; cout << “\nthe sine of the angle is “ << sin(angle) << endl; return 0;}//end main
6
Programmer Defined FunctionsTerminology
• Function Prototype– describes how a function is called
• Function Call• Function Arguments
– used in the function call• Function Definition
– function header– function body
• Formal Parameters– used in function definition
• Formal parameters must agree with arguments in order, number and data type, but the identifiers can be different.
7
Programmer Defined Functions
• Can be defined to– return a single value to the calling function– perform a task – change the value of multiple variables
8
Value Returning Functions
• A function returns a single value to the calling program
• The function header declares the type of value to be returned
• A return statement is required in the body of the function
10
//function definition: n! = n*(n-1)*(n-2)*…*1, // 0! is 1 by definition//Function fact returns n! //Function fact assumes n is non-negative integerint fact(int n) //function header, NO SEMICOLON{ int nfact = 1; while(n>1) { nfact = nfact*n;
n--; }//end while block return(nfact);}//end fact
Example - factorial function
11
Calling a function - a function prototype is required
int fact(int n); //function prototype, semicolon required// parameter identifier is optional
#include <iostream>using namespace std;int main(){ int n; cin >> n; if(n>=0)
cout<<n<<“! is ” <<fact(n)<<endl; //n is the argument else
cout <<“factorial not defined for negative numbers” <<endl;
return 0;}//end main
12
Calling a function- second example
int fact(int); //function prototype, //parameter identifier is optional
#include <iostream>using namespace std;int main(){ int n, factorial; cin >> n; if(n>=0) { factorial = fact(n); //function call
cout << n <<“! is ” << factorial << endl; } else
cout << “factorial not defined for negative numbers” << endl;
return 0;}//end main
13
2 Points of Style When Writing Value Returning Functions
• Formal parameters are used to pass information to the function. cin statements are usually not required.
• A return statement returns a value to the calling program. cout statements are usually not required.
• Use library functions as model (sin, log, etc)
14
void Functions
• A void function may be called to• perform a particular task (clear the screen) • modify data• perform input and output
• A void function does not return a value to the calling program
• return statement is optional• if a return statement is used, it has the following
form– return;
15
Example of void function//output formatted date//function definitionvoid print_date(int mo, int day, int year) //function header{ string month;
switch(mo){ case 1:
month = “January”; break;
case 2: month = “February”; break;
…case 12:
month = “December”;}//end switch
cout << month << ‘ ’ << day << “, << year << endl; return; //return is optional
} //end print date
16
Parameter Passing - pass by value
• Pass by value– the default in C++ (except when passing
arrays as arguments to functions)– formal parameter receives the value of the
argument– changes to the formal parameter do not affect
the argument
17
#include <iostream>using namespace std;int fact(int); //function prototypeint main(){ int n, factorial;
cin >> n;if(n>=0) { factorial = fact(n); //function call
cout << n <<“! is “ << factorial << endl;}//end if
return 0;}//end mainint fact(int n) //function header, NO SEMICOLON{ int nfact = 1; while(n>1) { nfact = nfact*n;
n--; }//end while block return(nfact);} //end fact
18
Parameter Passing - pass by reference
• Pass by reference– append an & to the parameter data type in
both the function prototype and function header
void get_date(int& day, int& mo, int& year)
– formal parameter receives the address of the argument
– any changes to the formal parameter directly change the value of the argument
19
Example - pass by reference
#include <iostream>using namespace std;
void swap(double&, double&); //function prototypeint main(){ double x=5, y=10; swap(x,y); //function call; x y are arguments cout >> “x = “ << x << ‘,’ << “ y= “ << y << endl; return 0;}//end main
Output is:x = 10, y = 5
20
Example - pass by reference
//Function swap interchanges the values of two variables//function definitionvoid swap(double& x, double& y) //function header{
double temp; //local variable temptemp = x;x=y;y=temp;return; //optional return statement
}//end swap
21
Practice! - What is the output?#include <iostream>using namespace std;void fun(int&, int&, int);int main(){ int c1=1, c2=2, c3=3;
cout << c1 << ‘,’ << c2 << ‘,’ << c3 << endl;fun(c1,c2,c3);cout << c1 << ‘,’ << c2 << ‘,’ << c3 << endl;fun(c3, c2, c1);cout << c1 << ‘,’ << c2 << ‘,’ << c3 << endl; return 0;
}void fun(int& a1, int& a2, int a3){ a1++;
a2++;a3--;
}
1,2,32,3,32,4,4
22
Storage Class and Scope
• Scope refers to the portion of the program in which it is valid to reference a function or a variable
• Storage class refers to the lifetime of a variable
23
Scope
• Local scope - a local variable is defined within a function or a block and can be accessed only within the function or block that defines it
• Global scope - a global variable is defined outside the main function and can be accessed by any function within the program file. Strongly discouraged!!