Thursday, May 2, 2019

Function in c++

Function 

A function is a group of statements that is executed when it is called from some point of the program.It is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.
 The following is its format:

return type name ( parameter1, parameter2, ...)
 {
 statements
 } 
where:
return type: return type is the data type specifier of the data returned by the function.
name: name is the identifier by which it will be possible to call the function.
parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.
s statement is the function's body. It is a block of statements surrounded by braces { }. 

Here you have the first function example:

#include <iostream>
 using namespace std;
int addition (int x, int Y) 
{
int r; 
r=X+Y; 
return (r);
}
int main ()
 {
int z; 
z = addition (5,3); 
cout << "The result is " << z;
 return 0;
}

Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list )

Example:
 int max(num1,  int num2);                                        

Parameter names are not important in function declaration only their type is required,

 so following is also valid declaration:
int max(int,int);                                        

Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.


No comments:

Post a Comment

Array

Arrays  An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by ad...