Functions
Functions
21
22 // Access via null-terminated character array
23 for (int i = 0; msg[i] != '\0'; ++i) {
24 cout << msg[i];
25 }
26 cout << endl;
27 return 0;
28 }
9.6 Exercises
[TODO]
10. Functions
10.1 Why Functions?
At times, a certain portion of codes has to be used many times. Instead of re-writing the codes many times, it is better to put them into a "subroutine", and "call"
this "subroutine" many time - for ease of maintenance and understanding. Subroutine is called method (in Java) or function (in C/C++).
Two parties are involved in using a function: a caller who calls the function, and the function called. The caller passes argument(s) to the function. The function
receives these argument(s), performs the programmed operations within the function's body, and returns a piece of result back to the caller.
10.2 Using Functions
area 1 is 3.63
area 2 is 14.52
area 3 is 32.67
In the above example, a reusable function called getArea() is defined, which receives a parameter (in double) from the caller, performs the calculation, and
return a piece of result (in double) to the caller. In the main(), we invoke getArea() functions thrice, each time with a different parameter.
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp1_Basics.html 31/44
1/13/2020 C++ Basics - C++ Programming Tutorial
In C++, you need to declare a function prototype (before the function is used), and provide a function definition, with a body containing the programmed
operations.
Function Definition
The syntax for function definition is as follows:
The parameterList consists of comma-separated parameter-type and parameter-name, i.e., param-1-type param-1-name, param-2-type param-2-
name,...
The returnValueType specifies the type of the return value, such as int or double. An special return type called void can be used to denote that the function
returns no value. In C++, a function is allowed to return one value or no value (void). It cannot return multiple values. [C++ does not allow you to return an
array!]
Take note that invoking a function (by the caller) transfers the control to the function. The return statement in the function transfers the control back to the
caller.
Function Prototype
In C++, a function must be declared before it can be called. It can be achieved by either placing the function definition before it is being used, or declare a so-
called function prototype.
A function prototype tells the compiler the function's interface, i.e., the return-type, function name, and the parameter type list (the number and type of
parameters). The function can now be defined anywhere in the file. For example,
You could optionally include the parameter names in the function prototype. The names will be ignored by the compiler, but serve as documentation. For
example,
// Function Prototype
double getArea(double radius); // parameter names are ignored, but serve as documentation
int max(int number1, int number2);
Function prototypes are usually grouped together and placed in a so-called header file. The header file can be included in many programs. We will discuss
header file later.
Another Example
We have a function called max(int, int), which takes two int and return their maximum. We invoke the max() function from the main().
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp1_Basics.html 32/44
1/13/2020 C++ Basics - C++ Programming Tutorial
optional. If there is no return statement, the entire body will be executed, and control returns to the caller at the end of the body.
In the above example, the variable (double radius) declared in the signature of getArea(double radius) is known as formal parameter. Its scope is within
the function's body. When the function is invoked by a caller, the caller must supply so-called actual parameters (or arguments), whose value is then used for the
actual computation. For example, when the function is invoked via "area1 = getArea(radius1)", radius1 is the actual parameter, with a value of 1.1.
Boolean Functions
A boolean function returns a bool value (of either true or false) to the caller.
Suppose that we wish to write a function called isOdd() to check if a given number is odd.
1 /*
2 * Test Boolean function (BooleanfunctionTest.cpp).
3 */
4 #include <iostream>
5 using namespace std;
6
7 // Function Prototype
8 bool isOdd(int);
9
10 int main() {
11 cout << boolalpha; // print bool as true or false
12 cout << isOdd(5) << endl; // true
13 cout << isOdd(6) << endl; // false
14 cout << isOdd(-5) << endl; // false
15 }
16
17 bool isOdd(int number) {
18 if (number % 2 == 1) {
19 return true;
20 } else {
21 return false;
22 }
23 }
This seemingly correct codes produces false for -5, because -5%2 is -1 instead of 1. You may rewrite the condition:
The above code produces the correct answer, but is poor. For boolean function, you should simply return the resultant bool value of the comparison, instead of
using a conditional statement, as follow:
int main() {
int number = -9;
if (isEven(number)) { // Don't write (isEven(number) == true)
cout << "Even" << endl;
}
}
10.3 Default Arguments
C++ introduces so-called default arguments for functions. These default values would be used if the caller omits the corresponding actual argument in calling the
function. Default arguments are specified in the function prototype, and cannot be repeated in the function definition. The default arguments are resolved based
on their positions. Hence, they can only be used to substitute the trailing arguments to avoid ambiguity. For example,
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp1_Basics.html 33/44
1/13/2020 C++ Basics - C++ Programming Tutorial
7 int fun2(int, int, int = 3);
8
9 int main() {
10 cout << fun1(4, 5, 6) << endl; // No default
11 cout << fun1(4, 5) << endl; // 4, 5, 3(default)
12 cout << fun1(4) << endl; // 4, 2(default), 3(default)
13 cout << fun1() << endl; // 1(default), 2(default), 3(default)
14
15 cout << fun2(4, 5, 6) << endl; // No default
16 cout << fun2(4, 5) << endl; // 4, 5, 3(default)
17 // cout << fun2(4) << endl;
18 // error: too few arguments to function 'int fun2(int, int, int)'
19 }
20
21 int fun1(int n1, int n2, int n3) {
22 // cannot repeat default arguments in function definition
23 return n1 + n2 + n3;
24 }
25
26 int fun2(int n1, int n2, int n3) {
27 return n1 + n2 + n3;
28 }
You should specify the default arguments in the function prototype (declaration). They can only be defined once (one-definition rule), and cannot be repeated in
the function definition.
Default argument is not absolutely necessary. The codes could be hard to maintain.
10.4 Function Overloading
C++ introduces function overloading (or function polymorphism, which means many forms), which allows you to have multiple versions of the same function
name, differentiated by the parameter list (number, type or order of parameters). The version matches the caller's argument list will be selected for execution. For
example,
*Name Mangling
To differentiate between different versions of an overloaded function, many compilers (such as GNU GCC) adopt a name mangling or name decoration scheme
for naming functions.
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp1_Basics.html 34/44
1/13/2020 C++ Basics - C++ Programming Tutorial
00000089 T __Z3funiii
......
Each of the function is identified via a prefix __Z, followed by an integer containing the number of characters of the function name (3 in this case for "fun"),
followed by the parameter type list (where i for int and d for double). For example, di means a double followed by an int; id for an int followed by a
double; iii for 3 ints.
You can choose to use the C's naming protocol by appending the keyword extern "C" to the function prototype. C does not support function overloading.
Thus, it does not need name mangling. It simply append an underscore in front of the function name. For example,
For example,
Pass-by-Value
In pass-by-value, a "copy" of argument is created and passed into the function. The invoked function works on the "clone", and cannot modify the original copy.
In C/C++, fundamental types (such as int and double) are passed by value. That is, you cannot modify caller's value inside the function - there is no side effect.
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp1_Basics.html 35/44
1/13/2020 C++ Basics - C++ Programming Tutorial
17 // Function definitions
18 // Return number+1
19 int inc(int number) {
20 ++number; // Modify parameter, no effect to caller
21 return number;
22 }
Pass-by-Reference
On the other hand, in pass-by-reference, a reference of the caller's variable is passed into the function. In other words, the invoked function works on the same
data. If the invoked function modifies the parameter, the same caller's copy will be modified as well.
In C/C++, arrays are passed by reference. That is, you can modify the contents of the caller's array inside the invoked function - there could be side effect in
passing arrays into function.
C/C++ does not allow functions to return an array. Hence, if you wish to write a function that modifies the contents of an array (e.g., sorting the elements of an
array), you need to rely on pass-by-reference to work on the same copy inside and outside the function. Recall that in pass-by-value, the invoked function works
on a clone copy and has no way to modify the original copy.
Array is passed into function by reference. That is, the invoked function works on the same copy of the array as the caller. Hence, changes of array inside the
function is reflected outside the function (i.e., side effect).
Use const whenever possible for passing references as it prevent you from inadvertently modifying the parameters and protects you against many programming
errors.
1 /* Search an array for the given key using Linear Search (LinearSearch.cpp) */
2 #include <iostream>
https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp1_Basics.html 36/44