08 Function
08 Function
2
Outline
❖ Function: definition, declaration, parameters, returned value
❖ Scope of variables
❖ Storage
3
Function
Function
❖ You should never write monolithic code
❖ Difficult to write correctly.
❖ Difficult to debug.
❖ Difficult to extend.
❖ Hard to maintenance
❖ Non-reusable
❖ Nonsense!
5
Function
❖ Definition: a group of statements that is given a name, and which can be called from
some point of the program.
Input
Function
Output
❖ All C++ functions (except the special case of the main function) should have:
q A declaration: this is a statement of how the function is to be called.
q A definition: this is the statement(s) of the task the function performs when called
Function Declaration
❖ A function is declared with the syntax:
returnVariableType functionName(parameter1, parameter2,
...,parameterN);
❖ Note the semi-colon at the end of the statement.
Function Definition
❖ A function is defined with the syntax:
retVariableType functionName(parameter1, parameter2,
...,parameterN)
{
statement(s);
}
Function
❖ C++ functions can:
q Accept parameters, but they are not required
q Return values, but a return value is not required
q Can modify parameters, if given explicit direction to do so
9
Function: No Return, No Parameters
#include<iostream>
using namespace std;
void displayMessage();
int main() {
displayMessage();
return 0;
}
void displayMessage() {
cout << "Welcome to CO1011!\n";
}
10
Functions with Parameters
#include<iostream>
using namespace std;
int main() {
displaySum(5, 10);
return 0;
}
11
Functions with Return
#include<iostream>
using namespace std;
int main() {
int sum = computeSum(5, 10);
printf("%d + %d = %d\n", 5, 10, sum);
return 0;
}
13
Pass Parameters
❖ Parameters: there are two ways to pass parameters to a function
❖ Value: the value will be copied to local variable (parameter) of the function
❖ Reference (only in C++): the parameter is associated with passed variable
❖ Passing by reference refers to passing the address of the variable
❖ Any change in the parameter affects the variable
14
Example
#include<iostream>
using namespace std;
void increment(int &input);
int main() {
int a = 34;
cout << "Before the function call a = " << a << "\n";
increment(a);
cout << "After the function call a = " << a << "\n";
return 0;
}
int main() {
const int size = 3;
int array[size] = { 33,66,99 };
arrayAsPointer(array, size);
return 0;
}
int main() {
cout << "The default box volume : " << computeBoxVolume() <<endl;
cout << "The second box volume : " << computeBoxVolume(10) << endl;
}
20
Example
float add(float a, float b);
int add(int a, int b);
double add(int a, double b);
24
Scope of Variables
#include<iostream>
using namespace std;
int main() {
cout << "global x = " << x << endl;
int y = 7; // local variable;
cout << "local y in main's scope = " << y << endl;
25
Unary Scope Resolution Operator
❖ It’s possible to declare local and global variables of the same name.
❖ Local variables take precedence over global variables
❖ The scope resolution operator :: is used to access to the global variable.
26
Example
#include<iostream>
using namespace std;
int main() {
int num = 10; //local variable
cout << "Local variable num = " << num << endl;
cout << "Global variable num = " << ::num << endl;
return 0;
}
27
Storage
Storage
❖ How your program is organized?
❖ What are common errors?
29
Storage
high address
command line arguments
////
and environment variables
stack
heap
initialized data
read from program file
text (code segment)
low address
30
Storage
❖ Code segment: contains executable code (binary code)
❖ Data segment:
❖ Initialized data: global, static, constants
❖ Uninitialized data
❖ Heap: contains allocated memory at runtime
❖ Stack: stores local variables, passed arguments, and return address
31
Function Call
#include <iostream>
using namespace std;
int main() {
int a = 10;
cout << a << " squared: " << square(a) << endl;
return 0;
}
int square(int x) {
return x * x;
}
Function Call
Function Call
Function Call
Storage
❖ Common errors:
❖ Use variables without initialization
❖ Memory fault
❖ Access restricted areas
❖ Memory corruption
36
Uninitialized variables
#include <iostream>
#include <math.h>
using namespace std;
float val;
int main() {
float x, y;
x = 0.5f;
cout << foo(x, y) << endl;
return 0;
}
37
Memory fault (access freed memory)
#include <iostream>
#include <math.h>
using namespace std;
int main() {
float x, y;
x = 0.5f;
y = 3.9f;
float *pRet = foo(x, y);
cout << *pRet << endl;
return 0;
}
38
Memory corruption
#include <iostream>
#include <math.h>
int main() {
char pStr [] = "This string will overwrite the local buffer";
foo(pStr);
return 0;
}
39
Summarise
❖ Learn about functions: how to define and use in the program
❖ How to pass parameters, understand scope of variables
❖ Memory organization of a program
40