Monday, February 29, 2016

Use of Functions in C

In C, a function is nothing but a self-contained block of code that can be accessed by specifying its name and providing the appropriate arguments to it from any part of the program. The argument list must be separated by commas. If the function does not require any arguments, then the function name will be followed by the empty parenthesis. The arguments used in the function call are known as actual arguments. The arguments in the first line of function definition are called formal arguments or actual parameters. The actual arguments must be of the same data type as the formal arguments. During the function call, values of actual arguments are copied into the formal arguments
Sometimes functions return values too. In that case, the value returned by the function can be assigned to a variable using assignment operator. Function calls may happen multiple times from different parts of the program and the actual argument may vary. But in all function calls the different arguments must be of the same data type as the formal argument and also the number and order of arguments must be same.
The general form of function prototypes looks like ...
  1. data_type function_name(data_type1 argument1, …, data_typeN argumentN);
and the function call will look like -
  1. function_name(argument1, argument2, , argumentN) ;

Example of a Function in C

A simple program with function call will look like this...
  1. #include<stdio.h>
  2. void print_hello();
  3.  
  4. void main()
  5. {
  6. print_hello();
  7. }
  8.  
  9. void print_hello()
  10. {
  11. printf("Hello world\n");
  12. }
This program just prints "Hello world" on the screen. The line after '#include' directive is called a function prototype. It declares that function 'print_hello' does not return anything and does not take any arguments. The function call is inside the 'main()'. After 'main', there is function definition which defines what the function does.

Placement of the Function

The function prototype should be defined before 'main' function, so that when the functions are called, compiler can decide whether the function exists or not or is on a different file. The function call can be placed in the 'main' function or even in another function body. The function body or definition can be placed before 'main' or after 'main' . If the function definition is placed before the invocation, then there is no need for function prototype.
In case the whole program is divided in multiple files, the function prototypes most likely to be included in the header file (files with '.h' extension). The file from which the function is invoked must include the header file containing the prototype. The function body in that case can be in a source file ('.c') or can be placed inside the header file as well.

No comments: