Functions
Syntax: type function-name(parameters)
{body of the function }
type means it's return type and if the function is not returning any value then its void. For Example if the function is returning an integer value then 'type'= 'int'. If no type is specified then Compiler assumes an integer value by default. So it is good to specify the Return type. Then in the parentheses is parameter_list. It can be leaved blank but it's up to the programmer whether he wants variables or not.
Program:
#include<iostream,.h>#include<conio.h>
void main()
{
clrscr();
void show();
{
cout<<"Hello World";
}
getch();
}
Output: Hello World
This will create a function 'show' inside the main. When the program will execute the compiler will go inside the function 'show' and will display the statement "Hello World" and will come out of the function and the program will terminate.
Function Prototype is the declaration of the function that tells the return type and the number of arguments and type of arguments that are going to be used in the program. If the function's definition is written first then there is no need for function prototype because function's definition is declaration itself( i.e. prototype of the function).
A function can be invoked in two manners:
1. Call by Value
2. Call by Reference
Call by Value
Call by value means calling the function by the matching of the number of arguments. The Call by Value copies the value of actual parameters(These are the parameters that appear in the function call statement or you can say in the 'main' function) into the formal parameters(These are in the function's definition). The function creates it's own copy of values and then uses it.
Program:
#include<iostream.h>#include<conio.h>
void main()
{
clrscr();
void show(int);
int num;
cout<<"Enter a Number: ";
cin>>num;
cout<<"Original Number: "<<num<<"\n";
show(num);
cout<<"Number after change: "<<num<<"\n";
getch();
}
void show(int num)
{
num= 5;
cout<<"Value of Number in function: "<<num<<"\n";
}
Output:
Enter a Number: 10Original Number: 10
Value of Number in function: 5
Number after change: 10
'show' function copies the value from the actual and shows it in formal. So by call be value does not changes the original values(i.e. actual parameters). So even after calling the function 'show' there will be no change in actual.
For Understanding Better:
(☞゚ヮ゚)☞ IMPRESSIVE ☜(゚ヮ゚☜)
ReplyDeleteThanks.
Delete