× Back Advantages Library functions User-Defined functions Function Declaration Function Definition Function Call return statement Function arguments Types of function Local, Global and Static variables Recursion Programs
← Previous Topic

Functions

Advantages of using functions

                    
int sum(int, int);
int main()
{
    int a, b, ans;
    printf("Enter two numbers: ");
    scanf("%d%d",&a, &b);
    ans = sum(a, b); // function call 
    printf("Sum is %d", ans);
    return 0;
}

int sum(int x, int y)
{
    int z;
    z = x + y;
    return z;
}
                    
                

Some features of above program

  1. The first statement is the declaration of the function which tells the compiler the name of the function and the data type of the arguments passed. This declaration is also called as prototype.
  2. The declaration of a function is not necessary if the output type is an integer value. In some c compilers declaratin is not required for all the function.
  3. Funcion call is the way of using the function. A function is declared once, defined once but can be used a numbber of times in the same program.
  4. When the compiler encounters the function call, the conrol of the program is tranferred to the function definition the function is then executed line by line and a value is returned at the end.
  5. At the end of the main program is the definition of the function, which can also be called as process.
  6. The function definiton does not terminate with a semicolon.
  7. A function may or may not return any value. Thus the presence of the return statement is not necessary. When the return statement is encountered, the control is immediately passed back to the calling function.
  8. All functions by default return int. But if the function has to return a particular type of data the type specifiers can be used along with the function name. long int fact(n)

Library Functions

                        
#include<stdio.h>
#include<math.h> 
int main()
{
    double n, s;
    printf("Enter a number : ");
    scanf("%lf", &n);
    s = sqrt(n);
    printf("The square root of %.2lf is : %.2lf", n, s);
    return 0;
}
/* 
    This program have three library functions - printf(), scanf() and sqrt()
*/
                        
                    

User-Defined Functions

Reference program ↓

                    
int sum(int, int); // function declaration / prototype
int main()
{
    int a, b, ans;
    printf("Enter two numbers: ");
    scanf("%d%d",&a, &b);
    ans = sum(a, b); // function call 
    // a and b are actual arguments
    printf("Sum is %d", ans);
    return 0;
}

int sum(int x, int y) // function definition
{
    int z;
    z = x + y;
    return z;
}
                    
                

Function Declaration

  • The calling function needs information about the called function.
  • If definition of the called function is placed before the calling function, then declaration is not needed.
                        
#include<stdio.h>
int sum(int x, int y) // function definition
{
    int s;
    s = x + y;
    return s;
}
int main()
{
    // body
}
                        
                    
  • Above the definition of sum() is written before main(), so main() knows everything about the function sum(). But generally the function main() is placed at the top of all, and other functions are placed after it. In this case, function declaration is needed. The function declaration is also known as the function prototype, and it informs the compiler about the following three things -
    1. Name of the function
    2. Number and type of arguments received by the function.
    3. Type of value returned by the function.
  • Function declaration tells the compiler that a function with these features will be defined and used later in the program.
    The general syntax of a function declaration is -
                            
return_type func_name(type1, type2, ...);
                            
                        

Function Definition

  • The function definition consists of the whole description and code of a function.
  • It tells what the function is doing and what are its input and outputs.
  • A function definition consists of two parts - a function header and a function body.
  • The general syntax of a function definition is -
                        
return_type func_name( datatype1 arg1, datatype2 arg2, ...)
{
    local variables declarations;
    statement;
    ...... 
    return(expression);
}
                        
                    
  • The first line in the function definiton is known as the function header and after this the body of the function is written enclosed in curly braces.
  • The return_type denotes the type of the value that will be returned by the function. The return_type is optional and if not omitted, it is assumed to be int by default.

Function Call

  • The function definition describes what a function can do, but to actually use it in the program the function should be called somewhere. A function is called by simply wiriting its name followed by the argument list inside the parentheses.
                        
func_name(arg1, arg2, ...);
                        
                    
  • These arguments arg1, arg2, ... are called actual arguments.
  • Here func_name is known as the called function while the function in which this function called is placed is known as the calling function.
  • When a function is called, the control passes to the called function.
  • If the function returns a value, then this function call can be used like an operand in any expression anywhere in the program.
                        
s = sum(a, b); /* Assigning the return value of sum() to variable s */
                        
                    

return statement

  • The return statement is used in a function to return a value to the calling function.
  • It may also be used for immediate exit from the called function to the calling function without returning a value.
  • This statement can appear anywhere inside the body of the function. There are two ways in which it can be used -
                        
return;
/* Above one is used to terminate the function without returning any value. */
return(expression);
/* Above return statement is used to terminate a function and return a value to the calling funtion. */
                        
                    

Function Arguments

  • the calling function sends some values to the called function for communication; these values are called arguments or parameters.

Actual arguments

  • The arguments which are mentioned in the function call are known as actual arguments, since these are the values which are actually sent to the called function.
  • Actual arguments can be written in the form of variables, constants or expressions or any function call that returns a value.
                            
func(x)
func(a*b, c*d+b)
func(1, 2, sum(a, b))
                            
                        

Formal arguments

  • The name of the arguments, which are mentioned in the function definition are called formal arguments since they are used just to hold the values that are sent by the calling function.
  • These formal arguments are simply like other local variables of the function which are created when the function call starts and are destroyed when the function ends. However there are two differences.
    • First is that formal arguments are declared inside parentheses while other local variables are declared at the beginning of the function block.
    • The second difference is that formal arguments are automatically initialzed with the values of the actual arguments passed, while other local variables are assigned values through the statements written inside the function definition.
  • The order, number and type of actual arguments in the function call should match with the order, number and type of formal arguments in the function definition.

Types of Functions on the basis of the arguments and return value

  1. Functions with no arguments and no return value.
  2. Functions with no arguments and a return value.
  3. Functions with arguments and no return value.
  4. Functions with arguments and a return value.

Functions with no arguments and no return value

  • Functions that have no arguments and no return value are written as ↓
                        
void func(void);
main()
{
    ...... 
    func();
    ......
}
void func(void)
{
    ..... 
    statement;
    ..... 
}
                        
                    

Functions with no arguments but a return value

  • These types of functions do not receive any arguments but they can return a value.
                        
int func(void);
main()
{
    int r;
    ..... 
    r = func();
    ..... 
}
int func(void)
{
    ...... 
    ......
    return (expression);
}
                        
                    

Function with arguments but no return value

  • These types of functions have arguments hence the calling function can send data to the called function but the called function does not return any value.
                        
void func(int, int);
main()
{
    ..... 
    func(a, b);
    .....
}
void func(int c, int d)
{
    ..... 
    statements 
    .....
}
                        
                    

Function with arguments and return value

  • These types of functions have arguments, so the calling function can send data to the called function, it can also return any value to the calling function using return statement.
                        
int func(int, int);
main()
{
    int r;
    ...... 
    r = func(a, b);
    ..... 
    func(c, d);
}
int func(int a, int b)
{
    ...... 
    ...... 
    return (expression);
}
                        
                    

Local, Global and Static Variables

Local Variables

  • The variables that are defined within the body of a function or a block, are local to that function block only and are called local variables.
                        
func()
{
    int a, b;
    ..... 
    ..... 
}
                        
                    
  • Here a and b are local variables which are defined within the body of the function func().
  • Local variables can be used only in those functions or blocks, in which they are declared.
  • The same variable may be used in different functions. For example ↓
                        
func1()
{
    int a=2, b=4;
    ...... 
    ...... 
}
func2()
{
    int a = 15, b = 20;
    ..... 
    ..... 
}
                        
                    
  • Here values of a = 2 and b = 4 are local to the function func1() and a = 15 and b = 20 are local to the function func2().

Global Variables

  • The variables that are defined outside any function are called global variables.
  • All function in the program can access and modify global variables.
  • It is used to declare a variable global if it is to be used by many functions in the program.
  • Global variables are automatically initialized to 0 at the time of declaration.
  • Program to understand the use of global variables ↓
                        
#include<stdio.h>
int a, b = 6;
main()
{
    printf("Inside main() : a = %d, b = %d\n", a, b);
    func1();
    func2();
}
void func1(void)
{
    printf("Inside func1() : a = %d, b = %d\n", a, b);
}
void func2(void)
{
    int a = 8;
    printf("Inside func2() : a = %d, b = %d\n", a, b);
}
                        
                    

OUTPUT ↓

                        
Inside main() : a = 0, b = 6
Inside func1() : a = 0, b = 6
Inside func2() : a = 8, b = 6
                        
                    
  • Here a and b are declared outside all functions hence they are global variables.
  • The variable a will be initialized to 0 automatically since it is a global variable.
  • Now we can use these variables in any function.
  • In func2(), there is a local variable with the same name as global variable. Whenever there is a conflict between a local and global variable, the local variable gets the precedence.
  • So inside func2() the value of local variable gets printed.

Static Variables

  • Static variables are declared by writing keyword static in front of the declaration.
                        
static type var_name;
                        
                    
  • A static variable is initialized only once and the value of a static variable is retained between function calls. If a static variable is not initialized then it is automatically initialized to 0.
  • Program to understand the use of static variables ↓
                        
#include<stdio.h>
main()
{
    func();
    func();
    func();
}
void func(void)
{
    int a = 10;
    static int b = 10;
    printf("a = %d    b = %d\n", a, b);
    a++;
    b++;
}
                        
                    
                        
a = 10    b = 10
a = 10    b = 11
a = 10    b = 12
                        
                    
  • Here 'b' is a static variable. First time when the function is called 'b' is initialized to 10.
  • Inside the same function the value of 'b' becomes 11. This value is retained and when next time the function is called value of 'b' is 11 and the initializaion is neglected.
  • Similarly when third time function is called, value of 'b' is 12. Note that the variable 'a', which is not static is initialized on each call and its value is not retained.

Recursion

                    
main()
{
    ..... 
    rec();
    .....
}
rec()
{
    ...... 
    ...... 
    rec();  ----> recursive call
    ......
}
                    
                

Before writing a recursive function for a problem we should consider these points-

  1. We should be able to define the solution of the problem in terms of similar type of smaller problem. At each step we get closer to the final solution of our original problem.
  2. There should be a terminating condition to stop recursion.

Passing arrays to functions

                        
#include <stdio.h>
float avg(int arr[], int s);
int main()
{
    int arr[6] = {1, 2, 3, 4, 5, 6};
    printf("The average is : %.2f", avg(arr, sizeof(arr) / sizeof(int)));
    return 0;
}
float avg(int arr[], int s)
{
    float avg;
    int sum = 0, i;
    for (i = 0; i < s; i++)
    {
        sum += arr[i];
    }
    return (float)sum / s;
}
                        
                    
                        
#include <stdio.h>
int max(int arr[], int s);
int min(int arr[], int s);
int main()
{
    int arr[6] = {1, 2, 3, 4, 5, 6};
    printf("The Maximum number is : %d\n", max(arr, sizeof(arr) / sizeof(int)));
    printf("The Minimum number is : %d\n", min(arr, sizeof(arr) / sizeof(int)));
    return 0;
}
int max(int arr[], int s)
{
    int i, max = arr[0];
    for (i = 1; i < s; i++)
    {
        if (arr[i] > max)
            max = arr[i];
    }
    return max;
}
int min(int arr[], int s)
{
    int i, min = arr[0];
    for (i = 1; i < s; i++)
    {
        if (arr[i] < min)
            min = arr[i];
    }
    return min;
}
                        
                    

Passing strings to functions

                        
#include <stdio.h>
void printit(char words[])
{
    printf("The words are : %s", words);
}
int main()
{
    char words[20] = "hehe";
    printit(words);
    return 0;
}
                        
                    

Pre-processor

Macro Substitution directive

                        
#define MAX 500
#define sqrt(x) x*x // macro with arguments
                        
                    

Programs

                        
#include<stdio.h>
main()
{
    int num;
    printf("Enter a number : ");
    scanf("%d", &num);
    printf("Factorial of %d is %ld\n", num, fact(num));
}
long fact(int n)
{
    if (n == 0)
        return 1;
    else 
        return (n * fact(n-1));
}