Saturday, April 2, 2016

Function in C


What are functions in C programming language?


In C programming language, functions are specific block of code that perform a number of predefined instruction to complete a particular task. In C programming User can either use the built-in library functions or can create its own custom functions which generally requires a prototype (function declaration) in start of the c program.
In C language, function calling is done by writing function name with opening and closing round brackets followed with semicolon. E.g. display ();
Category of Functions in C Language:
There are basically four categories of function in C programming language.

Type 1: Obtaining Parameter and Returning a Value

int addnum (int num1, int num2)
{
return num1 + num2;
}

Type 2: Obtaining Parameter but No Returning Value

void add(int num1, int num2)
{
printf("%d", num1+num2);
}

Type 3: Not Obtaining Parameter but Returning a Value

int add()
{
int num1, int num2;
num1 = 1;
num2 = 2;
return num1 + num2;
}

Type 4: Not Obtaining Parameter and No Returning Value

void add()
{
int num1, int num2;
num1 = 1;
num2 = 2;
printf("Result : %d",num1+num 2);;
}

Parameters in C functions


Below are the two ways used for passing parameter in C programming Language:
Pass by Value in c
In this type, a copy of the data is made and stored by way of the name of the parameter. The value is directly passed into the function. Any changes to the parameter have NO effect on data in the calling function.
Pass by Reference in c
A reference parameter "refers" to the original data in the calling function. Here the address of the value is passed into the function. Any changes to parameter will affect the original parameter.

passing  by value example. (Notice no &) 
   
void
doit( int  x )
{
x = 100;
Passing by reference example (Notice no “&“sign) 
   
void
doit( int & x )
{
x = 100; 
        } 

0 comments:

Post a Comment