Mark As Completed Discussion

Functions in C++

In C++, a function is a block of code that performs a specific task. Functions are used to break down a program into smaller and more manageable pieces, making the code more organized and modular.

Defining a Function

To define a function in C++, you need to specify the function's return type, name, and parameters (if any). The return type indicates the data type of the value that the function returns, if any.

Here's an example of a function that calculates and returns the sum of two numbers:

TEXT/X-C++SRC
1// Function to add two numbers
2int add(int a, int b) {
3  return a + b;
4}

In the code above, the function add takes two integer parameters a and b and returns their sum.

Calling a Function

To call a function in C++, you need to use the function name followed by parentheses. If the function has parameters, you need to provide the values for the parameters.

Here's an example of calling the add function from the previous example:

TEXT/X-C++SRC
1int num1 = 5;
2int num2 = 10;
3int sum = add(num1, num2);

In the code above, the add function is called with the values of num1 and num2 as arguments, and the returned sum is stored in the variable sum.

Output

The console output of the above example will be:

SNIPPET
1The sum of 5 and 10 is: 15
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment