Function in C++

Functions are primarily used to provide code reusability, which saves computational time and ensures that code is well-structured and clean. Functions also increase code readability since the same set of operations does not need to be written again and again. Functions take the information required to perform a task as the input parameter(s), perform the required operations on these parameters, and then return the final answer.

svg viewer

Code

In the example below, the function DoubleTheNumber takes an integer variable number and returns an integer by doubling its value.

Remember: you can provide more parameters separated by a comma (,).

#include <iostream>
using namespace std;
// Function
int DoubleTheNumber ( int number ){
int temp = number + number;
return temp;
}
int main() {
// calling function
cout << DoubleTheNumber(10);
return 0;
}

Calling a function

In line 12, we are executing the function by calling it and passing the appropriate parameter to it. Since the DoubleTheNumber function returns a value, ​we print it.

Void functions

void functions are those functions that​ are not supposed to return any value.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved