Lecture 8-C++ Functions
Lecture 8-C++ Functions
Introduction
We can break our C++ code into smaller chunks called functions. A function has a return type, a
name, a list of parameters in a declaration, and an additional function body in a definition. A simple
function definition is:
return_type function_name(arguments) {
statement;
statement;
return something;
}
Therefore; a function is a set of statements that take inputs, do some specific computation, and
produce output. The idea is to put some commonly or repeatedly done tasks together and make
a function so that instead of writing the same code again and again for different inputs, we can
call the function.
In simple terms, a function is a block of code that only runs (performs a specific task) when it is
called.
For example; suppose we need to create a program to create a circle and color it. We can create
two functions to solve this problem:
Thus, dividing a complex problem into smaller chunks makes our program easy to understand
and reusable.
1|Page
@myco…TCBE 2202 Computing for Civil Engineering
Below are an example of function declarations and definition.
Syntax:
2|Page
@myco…TCBE 2202 Computing for Civil Engineering
Program: Adding Two Numbers; this add function computes the sum of two numbers
#include <iostream>
using namespace std;
int add (int a, int b)
{
int c;
c = a + b;
return (c);
}
int main ()
{
int x, y;
x = 10;
y = 5;
int z = add (x, y);
cout<<"The sum is "<< z;
return 0;
As you can see in the above code, we created a function called add which takes two input
parameters a and b of type integer. This add function adds the two integer numbers it received as
input parameters and stores the result in variable c and returns that result.
Now see the main function. From the main function, we are calling the add function and while
calling the add function we are passing two parameters i.e. x and y (actually we are passing the
values stored in x and y) and these parameters’ values will go into a and b. The add function then
adds these two values and returns the result to the calling function (the function is called the add
method) i.e. the main method. The main method then store the result coming from the add method
into the variable z and then print the result on the output window.
As you can see in the above code, we are passing two values x and y to the add function which is
taking two parameters (a and b). The parameters (x and y) which are passing to the add function
are called Actual Parameters. The parameters (a and b) which are taken by the add method are
called Formal Parameters. When we call the add method the values of actual parameters are copied
to the formal parameters. So, x value i.e. 10 is copied to a, and y value i.e. 5 is copied to b.
Different Parts of a Function in C++ Language:
• Return Type: Function returning the value in which data type. It can be void if the function
returns nothing
• Name of the function: It is the identifier for the function name.
• Parameters/Arguments: Argument is the variables that the function will use. (can be
void)
• Body: this is the main logic of the function.
• Return Statement: if the return type is not null then the function will return a variable
according to the return type.
3|Page
@myco…TCBE 2202 Computing for Civil Engineering
Types of Functions
There are two types of function:
1. Standard Library Functions: Predefined in C++
2. User-defined Function: Created by users
Library Function
Library functions are also called “builtin Functions“. These functions are a part of a compiler
package that is already defined and consists of a special function with special and different
meanings. Builtin Function gives us an edge as we can directly use them without defining them
whereas in the user-defined function we have to declare and define a function before using them.
For Example: sqrt(), setw(), strcat(), etc.
Main Function
The main() function is a special function. Every C++ program must contain a function named
main. It serves as the entry point for the program. The computer will start running the code from
the beginning of the main function.
Types of Main Functions
1. Without parameters:
// Without Parameters
int main() { ... return 0; }
2. With parameters:
// With Parameters
int main(int argc, char* const argv[]) { ... return 0; }
The reason for having the parameter option for the main function is to allow input from the
command line. When you use the main function with parameters, it saves every group of
characters (separated by a space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return
statement in the code. The number that is returned is used to inform the calling program what
the result of the program’s execution was. Returning 0 signals that there were no problems.
4|Page
@myco…TCBE 2202 Computing for Civil Engineering
1. C++ Library Functions
Library functions are the built-in functions in C++ programming. Programmers can use library
functions by invoking the functions directly; they don't need to write the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc. In order to use library
functions, we usually need to include the header file in which these library functions are defined.
For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include
the header file cmath.
Example: C++ Program to Find the Square Root of a Number
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double number, squareRoot;
number = 25.0;
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Run Code
Output
Square root of 25 = 5
In this program, the sqrt() library function is used to calculate the square root of a number. The
function declaration of sqrt() is defined in the cmath header file. That's why we need to use the
code #include <cmath> to use the sqrt() function.
To learn more, visit C++ Standard Library functions; at https://www.programiz.com/cpp-
programming/library-function
5|Page
@myco…TCBE 2202 Computing for Civil Engineering
Categories of the Standard Function Library
The standard function library is divided into the following categories;
• I/O,
• String and character handling,
• Mathematical,
• Time, date, and localization,
• Dynamic allocation,
• Miscellaneous,
• Wide-character functions,
The table below shows some examples of standard Library functions in the first four categories.
No. Function name Purpose
C++ Mathematical Functions Header file: #include<cmath>
cos() returns Cosine of the Argument
sin() returns Sine of the Argument
tan() returns Tangent of the Argument
sinh() returns hyperbolic sine of an angle
exp() returns exponential (e) raised to a number
log() returns Natural Logarithm of a Number
trunc() truncates the demical part of a number
etc.
String and character handling Header file: #include<cstring>
strtol() converts a string to number
atol() converts String to Integer
strtod() returns string float to double
atof() converts String to Double
wctomb() converts wide character to a multibyte character
mbtowc() converts multibyte character to a wide character
etc.
I/O Header file: #include<iostream>
cin accepts input from the user
cout displays output to output device i.e monitor
wcin accepts input in wide character type
wcout displays wide characters (Unicode) to screen
etc.
Time, date, and localization Header file: #include<ctime>
time() returns current calendar time
clock() returns processor time consumed by program
difftime() computes difference between two times in seconds
asctime() converts calendar time to character representation
etc.
Etc.
6|Page
@myco…TCBE 2202 Computing for Civil Engineering
2. C++ User-defined Function
C++ allows the programmer to define their own function. A user-defined function groups code to
perform a specific task and that group of code is given a name (identifier). When the function is
invoked from any part of the program, it all executes the codes defined in the body of the function.
// function declaration
void greet() {
cout << "Hello World";
}
Here,
• the name of the function is greet()
• the return type of the function is void
• the empty parentheses mean it doesn't have any parameters
• the function body is written inside {}
Note: We will learn about returnType and parameters later in this tutorial.
Calling a Function
In the above program, we have declared a function named greet(). To use the greet() function, we
need to call it.
Here's how we can call the above greet() function.
int main() {
// calling a function
greet();
7|Page
@myco…TCBE 2202 Computing for Civil Engineering
How Function works in C++
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
return 0;
}
Run Code
Output
Hello there!
Function Parameters
As mentioned above, a function can be declared with parameters (arguments). A parameter is a
value that is passed when declaring a function. For example, let us consider the function below:
8|Page
@myco…TCBE 2202 Computing for Civil Engineering
Here, the int variable num is the function parameter. We pass a value to the function parameter
while calling the function.
int main() {
int n = 7;
return 0;
}
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
return 0;
}
Run Code
Output
9|Page
@myco…TCBE 2202 Computing for Civil Engineering
In the above program, we have used a function that has one int parameter and
one double parameter. We then pass num1 and num2 as arguments. These values are stored by
the function parameters n1 and n2 respectively.
Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.
Return Statement
In the above programs, we have used void in the function declaration. For example,
void displayNumber() {
// code
}
This means the function is not returning any value. It's also possible to return a value from a
function. For this, we need to specify the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a function.
For example,
10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Here, we have the data type int instead of void. This means that the function returns an int value.
The code return (a + b); returns the sum of the two parameters as the function value.
The return statement denotes that the function has ended. Any code after return inside the function
is not executed.
Example 3: Add Two Numbers
#include <iostream>
// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;
return 0;
}
Run Code
Output
100 + 78 = 178
In the above program, the add() function is used to find the sum of two numbers.
• We pass two int literals 100 and 78 while calling the function.
• We store the returned value of the function in the variable sum, and then we print it.
11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Working of C++ Function with return statement;
Notice that sum is a variable of int type. This is because the return value of add() is of int type.
Function Prototype
In C++, the code of function declaration should be before the function call. However, if we want
to define a function after the function call, we need to use the function prototype. For example,
// function prototype
void add(int, int);
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}
// function definition
void add(int a, int b) {
cout << (a + b);
}
12 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
This provides the compiler with information about the function name and its parameters. That's
why we can use the code to call a function before the function has been defined.
#include <iostream>
// function prototype
int add(int, int);
int main() {
int sum;
return 0;
}
// function definition
int add(int a, int b) {
return (a + b);
}
Run Code
Output
100 + 78 = 178
The above program is nearly identical to Example 3. The only difference is that here, the function
is defined after the function call. That's why we have used a function prototype in this example.
13 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Benefits of Using User-Defined Functions
• Functions make the code reusable. We can declare them once and use them multiple times.
Reusable codes can also be used in other programs.
• Functions make the program easier as each small task is divided into a function. A large
program can be divided into smaller modules. Hence, a large project can be divided among
many programmers.
• Functions increase readability. The program will be easier to understand, maintain, and
debug.
Understanding the main() function in C/C++.
The main () function is an identifier in the program which indicates the starting point of program
execution. The main () function is a user-defined function with the pre-implemented signature of
the linker. Always linker will be searching to start the program from main() only that’s why main()
function should be required.
Without using the main() function we can design the program but we can’t execute it because
compilation can be a success but the execution is a failure (linker error will occur).
In any application only one main() function should be required, if we are placing more than one
main() function then the compiler will give an error i.e. multiple declarations for main().
Generally, the main function does not return any value that’s why the return type of the main
function can also be void. In implementation when we need to return the exit status of an
application then the main function return type should be an int.
The void main() function does not provide any existing status back to the OS. int main function
will provide existing status back to the operating system i.e. success or failure.
When we need to inform the existing status as success then need to return “0” i.e. return 0; exit
success. When we need to inform the exit status as a failure then the return value should be 1 i.e.
return 1; exit failure
When the main function return type is mentioned as an integer type then it is possible to return the
values from -32768 to 32767 but those are all meaningless exit statuses except 1 and 0. When the
user is terminated the program explicitly then the exit code is -1.
14 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Points to Remember About Functions in C++
1. Most C++ program has a function called main() that is called by the operating system when
a user runs the program.
2. Every function has a return type. If a function doesn’t return any value, then void is used as a
return type. Moreover, if the return type of the function is void, we still can use the return
statement in the body of the function definition by not specifying any constant, variable, etc.
with it, by only mentioning the ‘return;’ statement which would symbolize the termination of
the function as shown below:
Function Declaration
15 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering