C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq
Dec 21, 2015
Content2
C++ Modules Function syntax Function parameters and return types Defining functions within programs Using and invoking function Function prototypes Function, file, and block scope Function signature Argument coercion Function Overloading Reference parameters Passing arguments (pass-by-value, pass-by-reference) Common errors
Modules
Blocks of codes with an independent functionality.
Written and tested separately.
Combined to form a complete program.
Modules either control or general:
Control
Called “Main”
each program include only one control module.
General
Perform manipulations on data e.g. calculation, print, read and
validation.
3
C++ Modules
All Modules in C++ are called “functions”
called methods or procedures in other languages.
Functions can be
Programmer-defined.
Built-in: pow, sqrt, .. etc.
Advantage
make programs easier to write, test, debug and maintain.
4
Functions Syntax5
ReturnType FctName(Parameter List)
{
action1;
action2;
..
actionN;
return value ;
}
Function Header
Function Body
321
1
2
Function Name and Return Type
Function name follows rules of naming identifiers as variables and
constants.
Function return ONLY one value.
Function return types: Built-in data types. User-defined data types. Nothing is returned by using keyword void.
6
int f1(Parameter List){
return value ;
}
void f2(Parameter List){
return;
}
void f2(Parameter List){
}
Function Parameters
Provide the communication links between the main program and its
functions.
Parameters declared in the function header within parenthesis.
Either have a single, multiple parameters or have no parameters.
List of a parameters are separated by commas.
Each parameter must be defined as follows:
DataType parameterName
7
char f1(int x, int y){
return value ;
}
Problem
Write a program that asks the user for the exam grade and prints a
message indicating if the user has passed the exam or not.
Can you solve the problem using functions ?
8
#include <iostream>using namespace std; int main(){ int grade;
cout<<"Enter your grade:\n"; cin>>grade;
if (grade>60) cout<<"You passed"; else cout<<“You failed";
return 0;}
1 -Selecting Functions
Divide the program into tasks:
Read student grade.
Print appropriate message.
Naming functions:
Read_Grade
Display_Msg
main
9
Read_Grade Display_Msg
main Fct
2-Analyzing Flow of Control10
Read_Grade Display_Msg
main Fct Start here
Invo
ke to
read
inpu
t fro
m u
ser
1
2
Ret
urn
the
inpu
t rea
d fro
m th
e us
er
3
Invoke to display message A
ND
send
the grade returned by Read_G
rade
4
Display m
essage on screen
AN
D return control to M
ain
5
return 0 ;6
3-Defining Functions
For each function decide on: Possible Parameter List Possible Return Value
int Read_Grade(){
}
void Display_Message(int g){
}
11
Read_Grade
Main FctInvoke to read
input from
user
Retu
rn the in
put read fro
m the user
Display_Msg
Main Fct
Invoke to display messag
e AN
D send
the grade return
ed by Read_
Grade
Disp
lay message on screen
AN
D return
control to Main
3-Defining Functions (cont.)12
Read_Grade Display_Msg
Main Fct
#include <iostream>using namespace std; int main(){ int grade;
cout<<"Enter your grade:\n"; cin>>grade;
if (grade>60) cout<<"You passed"; else cout<<“You failed";
return 0;}
Read_Grade
Display_Msg
3-Defining Functions (cont.)13
int Read_Grade(){ int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade;
return grade;}
void Display_Msg(int g){ if (g>60) cout<<"You passed"; else cout<<“You failed";}
grade scope
g scope
4-Using Functions14
#include <iostream>using namespace std;// ====== You Must Define your Modules before Main ======int Read_Grade(){ int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade;
return grade;}void Display_Msg(int g){ if (g>60) cout<<"You passed"; else cout<<“You failed";} // ====================== Main Fct ======================int main(){ // Invoke read module and store returned input // Invoke display module and pass the grade return 0;}
4-Using Functions (cont.)
In our example, all invokations occur in main function.
Invoking C++ functions syntax:
Write function name followed by ().
Within ( ) passing values (arguments) to parameters.
Functions could have No parameters FunctionName() One or more parameters FunctionName(v1,v2)
Capturing returned values
Functions return type could be void FunctionName() OR FunctionName(v1,v2) Non-void must use returned value in expression.
15
4-Using Functions (cont.)
Capturing returned values Non-void must use returned value in expression
Function Read_grade() returns an int
int n = Read_Grade();
if ( Read_Grade() == 3 ) …… … …
cout << Read_Grade();
16
4-Using Functions (cont.)
Each value passed in a function call is referred to as an Argument.
Arguments (Passed in a Function call) and parameters (defined in a
function header) MUST match in:
Number
Order
Data types
17
void Display_Msg(int g){ if (g > 60) cout<<"You passed"; else cout<<“You failed";}
int main(){
Display_Msg(87);
return 0;}
Argument
Parameter
Final Solution18
#include <iostream>using namespace std;// ====== You Must Define your Modules before Main ======int Read_Grade(){ int grade; //grade is a local variable cout<<"Enter your grade:\n"; cin>>grade;
return grade;}void Display_Msg(int g){ if (g>60) cout<<"You passed"; else cout<<“You failed";} // ====================== Main Fct ======================int main(){ int n = Read_Grade(); // Invoke read function Display_Msg(n); // Invoke display function return 0;}
Using Library Functions
Need to know the points below to write invokation of built-in functions
correctly:
Name of the function.
Number , type and order of parameters.
Type of return value if it has.
Header file.
Examples
Header File Function call Example Value
<cmath> pow(x,y) pow(2,3) 8 <iomanip> setprecision(n) setprecision(2)<< 1.2345 1.23
19
Function Prototype
Consists of the function's return type, name and parameter list
(number, types and order of parameters).
Also called function declaration.
Usually placed at the top of the program to tell the compiler that the
function exists.
Same as corresponding function header except that:
Parameter names are optional
Must end with a semicolon ;
20
Examples21
int square( int x )
{
return x * x;
}
void useLocal( void )
{
int x = 25;
cout << "\nlocal x is " << x << endl;
x++;
cout << "local x is " << x << endl;
}
void useLocal();
int square( int );
Compilation Error22
#include <iostream>using std::cin;using std::cout;using std::endl;
int main(){ int a = 10; cout << a << " squared: " << square( a ) << endl; return 0; }
int square( int x ){ return x * x; }
Error: function undeclared before use'square': identifier not found
Solution -123
#include <iostream>using std::cin;using std::cout;using std::endl;
int square( int x ){ return x * x; }
int main(){ int a = 10; cout << a << " squared: " << square( a ) << endl; return 0; }
Solution -224
#include <iostream>using std::cin;using std::cout;
using std::endl;
int square( int ); // prototype for function square
int main(){ int a = 10;
cout << a << " squared: " << square( a ) << endl; return 0; }
int square( int x ){ return x * x; }
Empty Parameter Lists
Specified by writing either void or nothing at all in parentheses.
int sum(); OR int sum(void);
25
Scope
Identifiers Variable or object. Function.
Scope of Identifier Portion of the program where an identifier can be used.
Types of scopes for an identifier: Function scope. File scope. Block scope.
26
File Scope
For an identifier declared outside any function or class
Identifier is “known” and can be used in all functions from the point at
which it is declared until the end of the file.
Examples
Global variables, function definitions and function prototypes placed
outside a function all have file scope.
27
Function Scope
Can be used anywhere in the function in which they appear.
Cannot be referenced outside the function body.
Examples
Local variables and function parameters.
28
Block Scope
Blocks are defined by the beginning left brace ( { ) and the
terminating right brace ( } ).
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.
29
30
#include <iostream>using std::cout;using std::endl;
int x = 1; // global variable
int main(){ int x = 5; // local variable to main
cout << "local x in main's outer scope is " << x << endl; { // start new scope int x = 7; // hides x in outer scope cout << "local x in main's inner scope is " << x << endl; } // end new scope cout << "local x in main's outer scope is " << x << endl;
return 0;}
File Scope (defined outside any class or function)
Function / Outer Block Scope (can be used only inside the outer block defined in Main)
Function / Inner Block Scope (can be used only inside the inner block defined in Main)
Function Signature
The portion of a function prototype that includes the name of the
function and the types of parameters.
Does not specify the function’s return type.
Functions in the same scope must have unique signatures.
31
int square( int ); Function Signature
Function Prototype
Compilation Error -132
#include <iostream>using std::cin;using std::cout;using std::endl;
int square( int x ){ return x * x; }
void square( int x) { cout<< x * x; }
int main(){ return 0; } // end main
• Two functions in the global(file) scope• They have the same signature:
square(int)• This results in a compilation error:
'square' : redefinition
Compilation Error -233
#include <iostream>using std::cin;using std::cout;using std::endl;
class Num {
int square( int x ){ return x * x; }
void square( int x) { cout<< x * x; } };
int main(){ return 0; // indicate successful termination} // end main
• Two functions in the class scope• They have the same signature:
square(int)• This results in a compilation error
'Num::square' : redefinition
Compilation Error -3
Arguments (in function call) and parameters (in function header)
must match in Number, Order, and Data Types.
34
#include <iostream> using namespace std;
int boxVolume( int length, int width, int height ) { return length * width * height; }
int main() { cout<< boxVolume(); // Error#1: 'boxVolume' : function does not take 0 arguments cout<< boxVolume(10); // Error#2: 'boxVolume' : function does not take 1 argument cout<< boxVolume(10,5); // Error#3: 'boxVolume' : function does not take 2 arguments cout<< boxVolume(10,5,2); return 0;}
Argument Coercion
Arguments (in function call) and parameters (in function header)
must match in Number, Order, and Data Types.
Promotion/Demotion may occur when the type of a function
argument does not match the specified parameter type.
35
1 -Argument Demotion36
#include <iostream> using namespace std;
int boxVolume( int length, int width , int height ) ;
int main() { cout<< boxVolume(10.5,5.7,2.4); return 0;}
int boxVolume( int length , int width , int height ) { return length * width * height; }
Warning: 'argument' : conversion from 'double' to 'int', possible loss of data
2 -Argument Promotion37
#include <iostream> using namespace std;
void boxVolume( double length, double width , double height ) ;
int main() { boxVolume(10,5,2); return 0;}
void boxVolume(double length , double width , double height ) { cout<< length * width * height; }
No Warning is issued when promotion of arguments occurs
3 -Return Type Demotion38
#include <iostream> using namespace std;
double boxVolume( double length, double width , double height ) ;
int main() { int r = boxVolume(10.5,5.7,2.3); return 0; }
double boxVolume(double length , double width , double height ) { return length * width * height; }
warning : conversion from 'double' to 'int', possible loss of data
4 -Return Type Promotion39
#include <iostream> using namespace std;
int boxVolume( int length, int width , int height ) ;
int main() { double r = boxVolume(10,5,2); return 0; }
int boxVolume(int length , int width , int height ) { return length * width * height; }
No Warning is issued when promotion of return values occurs
Function Overloading
Creating several functions of the same name that perform similar
tasks, but on different data types.
Overloaded functions have:
Same name.
Different signature.
Compiler selects proper function to execute based on number,
types and order of arguments in the function call.
40
41
#include <iostream>using std::cout;using std::endl;
// function square for int values int square( int x ) { cout << "square of integer " << x << " is "; return x * x; }
// function square for double values double square( double y ) { cout << "square of double " << y << " is "; return y * y; }
int main(){ cout << square( 7 ); // calls int version cout << endl; cout << square( 7.5 ); // calls double version cout << endl; return 0; }
42
#include <iostream>using std::cout;using std::endl;
// function multiply for two parameters int multi( int x, int y ) { return x * y; }
// function multiply for one parameter int multi( int y ) { return y * 1; }
int main(){ cout << multi( 7,5 ); // calls 2
parameter version cout << endl; cout << multi( 7 ); // calls 1 parameter
version cout << endl; return 0; }
43
#include <iostream>using std::cout;using std::endl;
// function multiply for two parameters int multi( int x, double y )
{ return x * y; }
// function multiply for two parameter but with different order
double multi( double y , int x) { return y * x; }
int main(){ cout << multi( 7,5.5 ); // calls
int,double version cout << endl; cout << multi( 7.5,3 ); // calls
double,int version cout << endl; return 0; }
Reference Variables44
// create an integer
int a ;
// Now create another name for the // same integer
int& b = a ;//ORInt &b = a ;
grab memory foran integer and labels it as "a"
"b" is just another label for the same memory
a
b
b is a "reference".
int& means "make a label to reference an integer"
a and b are synonyms for the same thing
Reference Variables (cont.) Can be used as aliases for other variables
An alias is simply another name for the original variable
All operations supposedly performed on the alias (i.e., the reference) are actually performed on the original variable
Must be initialized in their declarations Cannot be reassigned afterward
Example
int count = 1;
int &cRef = count;
cRef++;
45
1
count
1
count
cRef
2
count
cRef
46
#include <iostream>using std::cout;using std::endl;
int main(){ int x = 3; int &y = x; // y refers to (is an alias for) x
cout << "x = " << x << endl << "y = " << y << endl; y = 7; // actually modifies x cout << "x = " << x << endl << "y = " << y << endl; return 0; // indicates successful termination} // end main
x = 3y = 3x = 7y = 7
#include <iostream>using std::cout;using std::endl;
int main(){ int x = 3; int &y; // Error: y must be initialized
cout << "x = " << x << endl << "y = " << y << endl; y = 7; cout << "x = " << x << endl << "y = " << y << endl; return 0; }
Example #1
Example #2
Passing Arguments
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
47
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
void squareByReference( int &numberRef ) ;
Parameter name in the body of the called function actually refers to
the original variable in the calling function
48
Pass By Value49
#include <iostream>using std::cout;using std::endl;
int squareByValue( int ); // function prototype (value pass)
int main(){ int x = 2;
// demonstrate squareByValue cout << "x = " << x << " before squareByValue\n"; cout << "Value returned by squareByValue: " << squareByValue( x ) << endl; cout << "x = " << x << " after squareByValue\n" << endl;
return 0; }
int squareByValue( int number ) { return number *= number; // caller's argument not modified
}
2
x
2
number
Pass By Reference50
#include <iostream>using std::cout;using std::endl;
int squareByReference( int& ); // function prototype (value pass)
int main(){ int z = 4;
// demonstrate squareByReference cout << "z = " << z << " before squareByReference" << endl;
squareByReference( z ); cout << "z = " << z << " after squareByReference" << endl;
return 0; }
void squareByReference( int &numberRef ) { numberRef *= numberRef; // caller's argument modified }
4
z
numberRef
Common Errors
Compilation errors
Declaring function has parameters of the same type as char a,b instead of
char a, char b.
Invoking function before it is defined, e.g. when f1 invokes f2, f2 must be
defined before f1.
Attempting to use a function that has no return value in an expression.
Two functions in the same scope have the same signature.
Mismatching function header with function call OR function header with
function prototype in the number, type and order of parameters and
arguments.
51