Defining of Functions in C++

A function definition has two principal components:

  1. the first line (including the argument declaration), and
  2. the body of the function

In general, the first line can be written as:

data-type function_name(type 1 arg 1, type 2 arg 2, ..., type n arg n)

where,
data-type represents the data type of the item that is returned by the function,
function_name represents the function name, and
type 1, type 2, …, type n represents the data-type of the arguments arg 1, arg 2, …, arg n.

The data-types are assumed to be of the type int if they are not shown explicitly. However, the omission of the data type is considered poor programming practice, even if the data items are integers.

The arguments are called formal arguments, because they represent the names of the data items that are transferred into the function from the calling portion of the program. The names of the formal arguments need not be the same as the names of the actual arguments in the calling function of the program. However, each formal argument must be of the same data type, as the data item it receives from the calling function of the program.

The remainder of the function definition is a compound statement that defines the action to be taken by the function. This compound statement is referred to as the body of the function. Like any other compound statement, this statement can contain expression statements, other compound statements, control statements, and so on.

It should include one or more return statements, in order to return a value to the calling function of the program.

Example of Function Definition:

int addnumbers(int a, int b)
{
//body of the function enclosed in curly braces
int c;
c = a + b;
return c;
}

let us break the above example line by line and understand it,

int addnumbers(int a, int b)

Here, addnumbers is the name of the function having return type as int which means the function will return a value having integer data type.
The function addnumbers has two formal arguments i.e. a and b both having data type as int i.e., integer.

{
//body of the function enclosed in curly braces
int c;
c = a + b;
return c;
}

This is called the body of the function named addnumbers. The body of the function is enclosed in curly braces {}. The body of the function consist of multiple statements.

The above function is performing addition of the values present in variables a and b, and storing the value in variable c.

return c;

The above statement returns the result stored in the variable c to the calling function.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: