Wednesday

Function definition


Function definition

Function definition contains programming codes to perform specific task.
Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
                //body of function
}
Function definition has two major components:
Function definition has two major components:

Function declaration

1. Function declarator

Function declarator is the first line of function definition. When a function is invoked from calling function, control of the program is transferred to function declarator or called function.
Syntax of function declarator
return_type function_name(type(1) argument(1),....,type(n) argument(n))
Syntax of function declaration and declarator are almost same except, there is no semicolon at the end of declarator and function declarator is followed by function body.
In above example, int add(int a,int b) in line 12 is a function declarator.
Function body

2. Function body

Function declarator is followed by body of function which is composed of statements.
Passing arguments to functions
In programming, argument/parameter is a piece of data(constant or  variable) passed from a program to the function.
In above example two variable, num1 and num2 are passed to function during function call and these arguments are accepted by arguments a and b in function definition.
 

Arguments that are passed in function call and arguments that are accepted in function definition should have same data type. For example:

If argument num1 was of int type and num2 was of float type then, argument variable a should be of type int and b should be of type float,i.e., type of argument during function call and function definition should be same.

A function can be called with or without an argument.


Return Statement
Return statement is used for returning a value from function definition to calling function.
Syntax of return statement
return (expression);
          OR
     return;    
For example:
return;
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that value is stored in variable sum in main() function. The data type of expression in return statement should also match the return type of function.
 

Kindly Bookmark this Post using your favorite Bookmarking service:
Technorati Digg This Stumble Stumble Facebook Twitter
YOUR ADSENSE CODE GOES HERE

0 comments:

Post a Comment

Dont Forget for Commets

 

| C programing tutorials © 2009. All Rights Reserved | Template Style by My Blogger Tricks .com | Design by Brian Gardner | Back To Top |