Functions

Functions

Functions

In C++, a function is a block of code that performs a specific task. It allow you to modularize your code and reuse code blocks multiple times throughout your program. Here’s an example of a C++ function:

				
					#include<iostream>

//Function declaration

int add(int x, int y);

int main() {

   int a = 5;    int b = 7;

    // Function call

    int sum = add(a, b);

    std::cout << "The sum of " << a << " and " << b << " is "<< sum << std::endl;

    return 0;

}

//Function definition

int add(int x, int y) {

    return x + y;

}
​
				
			

In this example, we define a function called add that takes two integer arguments and returns the sum of the two integers.

We then declare the function before the main, which tells the compiler that the function exists and can be called from other parts of the program.

Inside the main, we declare two integer variables a and b, and then call the add function, passing in a and b as arguments. The return value of the add  is assigned to a variable called sum, which is then printed to the console using std::cout.

Finally, we define the add function after the main. The function takes two integer arguments x and y, and returns their sum using the + operator.

Note that the function declaration must match the function definition in terms of the number of arguments, the data types of the arguments, and the return type of the function.

Join To Get Our Newsletter
Spread the love