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.
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;// Functionint DoubleTheNumber ( int number ){int temp = number + number;return temp;}int main() {// calling functioncout << DoubleTheNumber(10);return 0;}
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
functionsvoid
functions are those functions that are not supposed to return any value.