0% found this document useful (0 votes)
4 views

C++ Functions

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C++ Functions

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

C++ Functions

In order to perform some task, number of statements is grouped together. This group of
statements is called as function in C++ programming.

1. Functions are written in order to make C++ program modular. We can break down the
complex program into the smaller functions.
2. In C++ group of statements is given a particular name called function name. Function is
called from some point of the program
3. C++ program must have at least 1 function and that function should be main.

Syntax of C++ Function Definition:

return_type function_name( parameter list )


{
body of the function
}

A C++ function definition consists of a function prototype declaration and a function body.

Return Type: return_type is the type of data that function returns. It is not necessary that
function will always return a value.

Function Name: It is the actual name of the function. The function name and the parameter list
together forms the signature of the function

Parameters: Parameters allow passing arguments to the function from the location where it is
called from. Parameter list is separated by comma

Function Body: The function body contains a collection of statements that define what the
function does.

Example

#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;
}
Output:
Sum is: 30

Explanation:

We know that each and every C++ program starts with the main function. In the C++ main
function we have declared the local variable inside the function.

// local variable declaration:


int a = 10;
int b = 20;
int result;

Now after the declaration we need to call the function written by the user to calculate the sum of
the two numbers. So we are now calling the function by passing the two parameters.

result = sum(a, b);

Now function will evaluate the addition of the two numbers. After the addition of two numbers
the value will be returned to the calling function. Returned value will be assigned to the variable
result.

You might also like