Sage-Code Laboratory
index<--

C++ Functions

The function is a group of statement that can have a name and can be executed on demand multiple times. In any program we must have at least one function and this has a special name, it is called main(). Functions are used to avoid repetitive code and to extend the language with new features without changing the core syntax.

Syntax:

This is how we declare a function in C++

return_type function_name(parameter_list) {
  //function body
  ...
}

What is a function?

The idea of function comes from mathematics but in IT sometimes a function can be just another synonym for sub-routine. A sub-routine is a set of statements encapsulated into a block of code with a name. Sub-routines can have input/output parameters and one or multiple results.

The role of a sub-routine is covered by functions. C++ do not have a reserved keyword to declare a function. In other languages we have: {"function", "fn", "def", "func"} but in C++ like in Java you have to specify only the name of the function and the result type. So a function in C++ is not actually a "function" but a "named section" of code.

function

Function Concepts

Example:

In next example we have two functions. One is called "main()" the other is called "sum()". We invoke the sum function from main function only once. The result is printed out to the console

#include <iostream>
using namespace std;
// function declaration
int sum(int num1, int num2);
int main () {
    // local variable declaration:
    int a = 10;
    int b = 20;
    int result;
    // calling a function to get result.
    result = sum(a, b);
    cout << "Sum is : " << result << endl;
    return 0;
}

// function returning the sum of two numbers
int sum(int num1, int num2) {
    // local variable declaration
    int res;
    res = num1 + num2;
    return res;
}

Notes:

Homework: Open this example on repl.it and run it: cpp-function What was the result?


Read next: Classes