C++ Functions

  • Post author:
  • Post category:C++
  • Post comments:0 Comments

Functions in C++

Functions are a fundamental part of C++ programming. A function is a block of code that performs a specific task and can be reused throughout a program. Functions allow us to break down complex tasks into smaller, more manageable pieces.

Let’s look at an example of a function in C++:

#include <iostream>

int add(int x, int y)
{
    return x + y;
}
 
int main()
{
    int x = 10;
    int y = 5;
 
    int z = add(x, y);
 
    std::cout << "x + y = " << z << std::endl;
 
    return 0;
}

Output

x + y = 15

In this example, we have declared a function called add() that takes two integers as parameters and returns the sum of those two integers. We have then called the add() function in the main() function and stored the result in the variable z. Finally, we have used the cout stream to print out the value of z.

Leave a Reply