Functions in C examples


Advertisements

Share



Learn function declaration, function call, types of functions, library & user defined functions, void, inline, recursive, reentrant functions in c with examples.

Function prototype, function definition, function call

Frequently asked topics, concepts.
  • What is a c programming function?
  •     C is a structured programming language. It divides the large problem into small modules called functions. Each function is written with a specific purpose. The basic purpose of writing functions is code re-usability. With functions it is easy to debug the program. Each function has three parts, function declaration/prototype, function definition, function call.
    A function is a set of statements that take inputs, do some specific computation and produces output.
    The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.
  • What is function prototype?
  •     Function prototype tells compiler about number of parameters function takes, data-types of parameters and return type of function. By using this information, compiler cross checks function parameters and their data-type with function definition and function call.
    If we ignore function prototype, program may compile with warning, and may work properly. But some times, it will give strange output and it is very hard to find such programming mistakes.
    Always declare a function prototype and its definition before it is called in the program.
  • What is function definition?
  •     A function definition actually defines the purpose for which the function is written. While writing a function definition we need to write the right arguments it takes as input and returns from it as output. Using the function input arguments logic is implemented inside the function definition.
    To illustrate the features of functions we have written a simple function addFunc.
    Program illustrating functions prototype, definition, call.
    
    #include <stdio.h>
    int addInt(int ,int );
    int main(){
      int a1 = 20,a2 = 30;
      printf("a1 + a2 = %d",addInt(a1,a2));
    }
    int addInt(int a,int b) {
      return a + b;
    }
    
    
  • function1.c program analysis
  •     Let's analyse function addFunc in function1.c. A function declaration is made to inform the compiler on type of arguments it takes, the type it returns. This information is provided in addFunc function prototype. What it says is addFunc function takes two integers as arguments and return an integer.
    In the addFunc function definition we wrote, when we add two integers we expect the result to be another integer. Hence we started with int data type. We named the function as addFunc. You can give any name to a function but it should reflect in some way the purpose for which it is written. Now in the arguments list addFunc function takes two integers which are included separated by a comma. Let's look at some very important rules to remember while writing a function definition.
    Following are the rules to follow while writing a function definition:
    • Inside a function definition only variables declared in function arguments or explicitly declared inside the function are accessible. So inside AddFunc function arguments a, b and explicitly declared variable r can only be accessed. If you try to use other variables inside the function addFunc, compiler will detect errors.
    • The variable returned from a function must match the data type of return variable. In addFunc case we know the result of two integers will be another integer. So the return data type of addFunc must be integer. We declared an integer variable r, stored the adding result of a and b, returned r from the function.
    • The data type of variable returned from function, used as function arguments must match as per the function prototype. In addFunc case the return type and function arguments as per prototype declared are int. Hence addFunc return data type is int and variables passed to the function are of int data type.
    • The number of arguments passed to the function in the definition and the order in which they are passed must match as per the function prototype. In addFunc case there are two int variables passed as arguments to the function addFunc as per its prototype. We have done exactly that while declaring the function addFunc.
        To use a function you must call it. If a function is not called the code inside the function definition is not executed. In our case to add two integers we must call addFunc. Following are the few rules to remember while calling a function.
    • The variable used to get output from the function should match the return data type of the function. So while calling addFunc function we used an integer variable "r" to get output from addFunc function.
    • The variables used as function arguments should match the variables that are passed while calling the function. So while calling addFunc, we have used two integer variables to pass to the function. Compiler will detect errors if the passed arguments data types do not match as per the defined function prototype.

    Library, User defined functions

    Frequently asked topics, concepts.
  • What are library functions?
  •     A function is called library function if it is already defined as part of any of the header file. If we want to use a function defined in any header file we just need to include the header file where the function is defined and then we need to call the function. In function1.c printf is already defined in stdio.h. Hence to include stdio.h is enough before calling it. We don't need to write the prototypes and definitions for these functions.
  • What are user defined functions?
  •     A function is called user defined function if it is not defined in any of the header file. User need to declare, define a user defined function before calling the function. In function1.c addInt, is an user defined function. Hence it is declared and defined separately before calling it from the main function.

    Startup, Cleanup functions

    Frequently asked topics, concepts.
  • What are startup and Cleanup functions?
  •     With GCC family of C compilers, we can mark some functions to execute before and after main(). So some startup code can be executed before main() starts, and some cleanup code can be executed after main() ends. For example, in the following program, myStartupFun() is called before main() and myCleanupFun() is called after main().
    Program illustrating startup and cleanup function.
    
    #include <stdio.h>
    
    /* Apply the constructor attribute to StartupFun() so that it
        is executed before main() */
    void StartupFun(void) __attribute__ ((constructor));
    
    
    /* Apply the destructor attribute to CleanupFun() so that it
       is executed after main() */
    void CleanupFun(void) __attribute__ ((destructor));
    
    
    /* implementation of myStartupFun */
    void StartupFun(void)
    {
        printf ("startup code before main()\n");
    }
    
    /* implementation of myCleanupFun */
    void CleanupFun(void)
    {
        printf ("cleanup code after main()\n");
    }
    
    int main()
    {
      printf("Here is my first statement\n");
      return 0;
    }
    
    

    return 0 vs exit(0)

    Frequently asked topics, concepts.
  • What is the difference between return 0 and exit(0)?
  •     return 0; is a statement that returns control back to the calling function. So functions called after the current function will continue to be executed. exit(0) is a system call which terminates the current process i.e the currently executing program. So any function called after the current function will not be executed.
    In main function return 0 or exit(0) are same but if you write exit(0) in different function then your program will exit from that position. Also returning different values from functions like return 1 or return -1 means that program is returning error.
    Program illustrating difference between return 0 and exit(0).
    
    #include <stdio.h>
    #include <stdlib.h>
    int func1();
    void func2();
    void func3();
    int main()
    {
      printf("Here is my main statement\n");
      func1();
      return 0;
    }
    int func1()
    {
      printf("Hello func1\n");
      func2();
      return 0;
    }
    void func2()
    {
      printf("Hello func2\n");
      exit(0);
      func3();
    }
    void func3()
    {
      printf("Hello func3\n");
    }
    
    

    void function, inline function

  • What are void functions?
  • void functions do not return a value when the function is called. Void functions have void as return data type and return control to the caller once the code inside it are executed. Void functions don't return anything to the caller function.
    Program illustrating the difference between void and non void function
    
    #include <stdio.h>
    void voidFunc(int ,int );
    int nonVoid(int ,int );
    int main() {
      int num1 = 3, num2 = 2, res;
      voidFunc(num1,num2);
      res = nonVoid(num1,num2);
      printf("The result is:%d\n", res);
      return 0;
    }
    int nonVoid(int a,int b)
    { /* nonVoid function definition */
      int res;
      res = ((a^2) + (b^2) + (2 *a *b));
      return res;
    }
    void voidFunc(int a,int b)
    { /* voidFunc function definition */
      int res;
      res = ((a^2) + (b^2) + (2 *a *b));
      printf("The result is:%d\n",res);
    }
    
    
    Let's analyse the above example program. Here both voidFunc and nonVoid functions does the same work. But nonVoid function returns the result to main function. So we captured the result of nonVoid function in variable res inside main function. But in the voidFunc case the function itself does not return anything to the calling function main. So once voidFunc function is executed, main executes the next line of code.
  • What are Inline functions?
  •     An Inline Function is As Fast As a Macro. By declaring a function inline, you can direct GCC to make calls to that function faster. One way GCC can achieve this is to integrate that function's code into the code for its callers. This makes execution faster by eliminating the function-call overhead. in addition, if any of the actual argument values are constant, their known values may permit simplifications at compile time so that not all of the inline function's code needs to be included. The effect on code size is less predictable. object code may be larger or smaller with function inlining, depending on the particular case.
    Program illustrating the use of Inline functions.
    
    #include <stdio.h>
    void inline test_inline_func1(int a, int b) 
    {
      printf ("a=%d and b=%d\n", a, b);
    }
    int inline test_inline_func2(int x) 
    {
      return x*x;
    }
    int main() {
      int tmp;
      test_inline_func1(2,4);
      tmp = test_inline_func2(5);
      printf("square val=%d\n", tmp);
      return 0;
    }
    

    Reentrant, Non-reentrant, recursive functions

  • What are Reentrant functions?
  •     A reentrant function is a function that can be used by more than one task without fear of data corruption. A reentrant function can be interrupted at any time and resumed at a later time without loss of data. Reentrant functions either use local variables (i.e. CPU registers or variables on the stack) or protect data when global variables are used. An example of a reentrant function is shown in below example.
    Program illustrating the reentrant function
    
    void strcpy(char *dest, char *src)
    {
        while (*dest++ = *src++) {
    ;
    }
    *dest = NUL;
    }
    
    
  • What are Recursive functions?
  •     A function which calls itself either directly or indirectly is called a recursive function. Let's say we want to calculate the factorial of a number. In this case we have to multiply the number with its previous number repeatedly.
    Program illustrtating the use of recursion.
    
    #include <stdio.h>
    #include <stdlib.h>
    int fact(int );
    int main() {
      int num = 5;
      int res;
      res = fact(num);
      printf("Factorial is %d\n",res);
      return 0;
    }
    int fact(int x)
    {
      if(x > 1)
      {
        return x * fact(x-1);
      }else
      {
        return 1;
      }
    }
    
    

    Exercises, Solutions

    Low
    Medium
    Medium
    Low
    Medium
    High
    Low
    Medium
    Medium

    Want to contribute a new article? Write and upload your article information .
    Share

     Articles

     C Programming

     Linux Software

     Test your skills:online tests

     C Programming

     Python Programming

     Linux Software

     Quantitative Aptitude

     Embedded System Software

     Search Code Snippets

     Popular C search examples

     Popular C search MCQs