Functions in {lang}
Quite often we need to perform a similar action in many places of the program.
For example, we need to show a nice-looking message when a visitor logs in, logs out and maybe somewhere else.
Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.
The syntax to declare a C++ function is:
returnType functionName (parameter1, parameter2,...) {
statements
}
Where:
- returnType is the type of the value returned by the function.
- functionName is the identifier by which the function can be called.
- parameters (as many as needed): Each parameter consists of a type followed by an identifier, with each parameter being separated from the next by a comma. Each parameter looks very much like a regular variable declaration (for example: int x), and in fact acts within the function as a regular variable which is local to the function. The purpose of parameters is to allow passing arguments to the function from the location where it is called from.
- statements is the function's body. It is a block of statements surrounded by braces { } that specify what the function actually does.
Let's have a look at an example:
void greet() {
cout << "Hello World";
}
Here:
- the name of the function is greet()
- the return type of the function is void, which means the function is not returning any value.
- the empty parentheses mean it doesn't have any parameters
- the function body is written inside {}
You can call or invoke this function by using its name followed by parentheses, like this: greet();
Each time the function is called it will print out the message Hello World on the dev console. All of the code between the curly braces will be executed every time the function is called.
Function arguments/parameters
We can pass arbitrary data to functions using parameters.
Parameters are variables that act as placeholders for the values that are to be input to a function when it is called.
When a function is defined, it is typically defined along with one or more parameters, which will be supplied by the calling code and can be used inside the function.
Here is a function with two string parameters, param1 and param2:
void testFun(string param1, string param2) {
cout << param1 << " " << param2 << "\n";
}
Then we can call testFun like this: testFun("Hello", "World");. We have passed two string arguments, Hello and World. Inside the function, param1 will equal the string Hello and param2 will equal the string World. Note that you could call testFun again with different arguments and the parameters would take on the value of the new arguments.
The return statement
In the above programs, we have used void in the function declaration. 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, like this:
int plusThree(int num) {
return num + 3;
}
// Inside main function:
int answer = plusThree(5);
Here, we have the data type int instead of void. This means that the function returns an int value.
answer has the value 8.
plusThree takes an argument for num and returns a value equal to num + 3.
The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer above):
Inside void functions, it is possible to use return without a value. That causes the function to exit immediately. For example:
void showMovie(int age) {
if (age < 16) {
return;
}
cout << "Showing you the movie";
}
In the code above, if age < 16 returns false, then showMovie won’t proceed to the cout.
Local Variables
A variable declared inside a function is only visible inside that function. Example:
void showMessage() {
string message = "Hello, I'm C++!"; // local variable
cout << message << "\n";
}
// Inside main function:
showMessage(); // prints "Hello, I'm C++!"
cout << message; // <-- Error! The variable is local to the function
Outer Variables
A function can access an outer global variable as well, for example:
string userName = 'John';
void showMessage() {
string message = 'Hello, ' + userName;
cout << message;
}
showMessage(); // prints "Hello, John"
The function has full access to the outer variable. It can modify it as well, for example:
string userName = 'John';
void showMessage() {
userName = "Bob"; // (1) changed the outer variable
string message = 'Hello, ' + userName;
cout << message;
}
cout << userName; // prints "John" (before the function call)
showMessage(); // prints "Hello, Bob" and modifies the userName variable
cout << userName; // prints "Bob" (the value was modified by the function)
Assignment
Follow the Coding Tutorial and let's write some functions.
Hint
Look at the examples above if you get stuck.