User Defined Functions ... continued

We begin here, with the general structure functions in C have

function-name(argument list)
argument declaration;
 local variable declarations;
 executable statement1;
 executable statement2;
 rerturn (expression);

All parts are not essential. Some may be absent. For example, the argument list and its associated argument declaration parts are optional. The declaration of local variables is required only when any local variables are used in the function.

A function can have any number of executable statements at all. For example:


The return statement is the mechanism for returning a value  to the calling function. This is also an optional statement. Its absence indicates that no value is being returned to the calling function.    

Argument List

The argument list contains valid variable names separated by commas. The list must be surrounded by parenthesis. The argument variables receive values from the calling function, thus providing a means for data communication from the calling function to the called function. Some examples of functions with arguments are :

sachinrulz(a, b, c)
mayurrulz(s, d, f)

All argument variables must be declared for their types after the function header and before the opening brace of the function body. Example:

float x;
int y;

Return Values And Their Types

A function may or may not send back any value to the calling function. If it does, it is done through the return statement. While it is possible to pass to the called function any number of values, the called function can only return one value per call, at the most we can have 


The first, the 'plain' return does not return any value; it acts much as the closing brace of the function. When a return is encountered, the control is immediately passed back to the calling function. An example of the use of a simple return is as follows:


The second form of return with an expression returns the value of the expression. For example,

int x,y;
 int p;
 p = x*y;

We could have also combined the last two statements as follows:


Now by default all functions return int type data. If a function wants to return some other type of value (can be float, character, string, structure, pointer, etc) whether it is user-defined or inbuilt data type, it can be achieved by giving a type specifier in the function header. Example:

double sum(w, r)
char rait(c)

When a value is returned it is automatically cast to the function's type. In functions that do computations using double, yet return int, the returned value will be truncated to an integer.

We will continue with the various categories in C functions, next time.  


More by :  Sachin Mehta

Top | Computing

Views: 3615      Comments: 0

Name *

Email ID

Comment *
Verification Code*

Can't read? Reload

Please fill the above code for verification.