Functions

What is a function?

 It is basically a self-contained block of code designed to perform a particular task whenever it is called. (In technical terms: a sub-routine or a module.)

 

Declaration:

return-type function-name(parameter list)

{

body of the function

}

 

  • return type can be any C data-type
  • function name is any valid C identifier
  • parameter list (or argument list) specifies the data type and name of each argument passed to the function

 

Function prototype/declaration

It merely specifies function name, return type, argument. It does NOT tell what the function does.

 

//function prototype

return-type function-name(parameter list);

 

Function definition

It actually defines the function i.e. it specifies exactly what the function performs.

 

//function definition

return-type function-name(parameter list)

{

body of the function      //contains the statements to be executed when function is invoked

}

  

Note:

  • As far as C is concerned function prototypes are not necessary. You can conveniently omit them from your code.  However, it is better to include them for the sake of clarity and easy documentation.
  • Function declaration always comes before the function definition. 

Return Types

A function when called/invoked may also return or generate or equate to a value (value here can be of any data type or even an object).

 

Recall the function prototype discussed earlier-

//function prototype

return-type function-name(parameter list);

 

If we carefully observe this declaration is similar to the declaration of any variable, as shown in figure.

 

Syntax of a function 

 

Thus we see that a function with a return value can be thought of a variable of type specified by the return value. Thus the return value of a function is the value the function takes.

 

To return a value from a function we use the return statement. return is a reserved keyword. Whenever a return statement is encountered in a function, the control is passed back to the calling function.

 

Syntax:

 

return  (expression) ;

 

Here the expression can be single value (constant), a variable, or even any logical/arithmetic/boolean expression etc.

 

Remark:

  • If we don’t want the function to return any value, we specify its return type as void.
  • In such cases we can use an empty return statement i.e. return; or exclude the return statement altogether.
  • A function can only return a single value

Argument/Parameters list

The parameters / arguments form a very important feature of the function.

 

Function flowchart

 

The argument list consists of independent single variable declarations separated by commas.

i.e 

function_name(data-type1 name1, data-type2 name2, data-type3 name3,....)

{

}

 

  • A function may contain any number of arguments.
  • A function may not take an argument at all. In this case we denote it by empty parentheses. 

Calling Functions

In the most layman terms, whenever we use the function in our program it is referred to as calling the function.

Example:-

 

print();

min(a,b,c);

max(a,b,c);

 

All these represent function calls.

 

Passing arguments to a function

Suppose we pass some arguments to a function. The function operates on these arguments and may alter their value. Now there can be two situations -

  • The changes made in the function are also reflected in the original variables (that were passed) - call by reference.
  • No change is observed in the variables that were passed - call by value.

 

Call by value

In this method of calling, only the values of the variables are passed and there is no link or reference whatsoever to the arguments variables.

Here the compiler creates a separate set of variables (corresponding to the arguments that were passed) for the function, and then the function operates on this copy of the arguments.

 

Call by reference

Call by reference is the second way of passing arguments to a subroutine. In this method, the address of an argument is copied into the parameter. Inside the subroutine, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

 

Example:

#include<stdio.h>

 

void swap_ref(int *a,int *b);

void swap_val(int a,int b);

 

 int main()

{

int a=3,b=6;

printf(“\na=%d  b=%d”,a,b);

swap_val(a,b);                                  //call by value

 

printf(“\na=%d  b=%d”,a,b);       //a and b will not be changed

swap_ref(&a,&b);           //here we pass the address of the actual //arguments

printf(“\n a=%d  b=%d”,a,b);      //a and b will reflect the changes

 

return 1;

}

 

void swap_ref(int *a, int *b)

{                                                                                              //function accepts the address

*a=*a+*b;                                                                          //and changes the values stored

*b=*a-*b;                                                                           //at these addresses                                     

*a=*a-*b;

}

void swap_val(int a, int b)                           

{

a=a+b;

b=a-b;

a=a-b;

}

 

 

Output will be as shown below –

 

Output

 

Download source code.

 

 

Passing arrays to functions

Arrays can also be passed to a function as argument. However for passing arrays only the array name is required. (Array name is actually a pointer to the first element of the array).

Thus arrays are always passed by reference to any function. Example-bubblesort

 

Why to use functions?

  • makes your code more efficient
  • the code becomes easy to understand
  • debugging is easy

 

Recursion

Whenever a function calls itself, it is called as recursion. It is important to realize that when using recursion there should be some sort of check which makes sure that this process does not go indefinitely. Consider the following code-

 

main()

{

printf(“\nthis is an example of recursion”);

main();

}

 

This program will terminate abruptly as soon it run out of stack space.

 

In other words, a typical recursive function is one which is defined in terms of itself such that when it calls itself recursively, each invocation gets a fresh set of all the automatic variables, independent of the previous set. Somewhere in the function a check condition (usually on the arguments) is used which when true forces the function to return without the recursive call being executed, thereby prevention an infinite program run.

 

main() as a Function

You might have observed that main() is also a function. Then the question arises that can we pass arguments to main function?

The answer is YES. However the number and types of arguments are fixed.

 

main(int argc, char *argv[])

 

These arguments are passed via the command line (hence also called command-line arguments) to the function. The syntax for invoking the program with command line parameters

 

path_to_program\program_name argument_list

 

The arguments are separated by whitespaces.

 argc – it the number of arguments passed to the program

*argv[] - array of the argument strings

 

Example - consider the following command executed in the command prompt:

 

c:\tc\bin\tcc  -c  test.cpp

 

In the above statement we are passing two arguments namely -c and test.cpp to the program tcc i.e argc =2 and argv is an array of the strings –c and test.cpp.