Functions:
A function is a subprogram that can be defined by the user in his/her program. It is a complete program by itself in the sense that its structure is similar to the main() function except the main name is replaced by the self-defined name of the function. Syntax of function is:
<type> <name> (arguments)
<type> is a type of value to be returned by the function. If no value returns then the keyword void is used.
<name> is a user-defined name of function.
(arguments)is a list of parameters(Parameter is the data that function received when we call)
Thus a function has the following four elements:
- A name: The name of the function has to be unique so that compiler can be identified.
- A body: The body of function contain valid c++ statements which defined the task perform by function
- A return type: The return type is the type of value that the function is able to return to the calling function.
- Arguments: The arguments and parameters contain the list of values of variables require from outside of the computer.
Four Types of function
Function with no return value and no parameters:void function_name ()
{
// Block of code;
}
Function with return value and no parameters:
int function_name ()
{
// Block of code;
return integer;
}
Function that cannot return but contains parameters:
void function_name (int x, int y)
{
// Block of code;
}
Function with return value and parameters:
int function_name (int x, int y)
{
// Block of code;
return int;
}
Function Prototyping
Function prototyping is similar to variables, all functions must be declared before used in the program.
<type> function_name ();
For example, the prototype for function add () can be written as:
int add (int x, int y);
It may be noted that the function prototype ends with a semicolon.
The function prototype is required for those function which is intended to be called before they are defined.
Calling a function
The function can be called or invoked from another function bu using its name. The function name must be followed by a set of actual parameters, enclosed in parentheses separated by a comma.
add(10, 20);
Example :
#include<iostream>
using namespace std;
int compare(int x ,int y)
{
//Function with return and aurguments
if(x>y)
return x;
else
return y;
}
int main()
{
int c;
c=compare(10 , 20);
//calling a function
cout<<c;
}
0 Comments