C Programming Functions

In this tutorial, you will be introduced to functions (both user-defined and standard library functions) in C programming. Also, you will learn why functions are used in programming.
Functions in C programming

A function is a block of code that performs a specific task.

Suppose, a program related to graphics needs to create a circle and color it depending upon the radius and color from the user. You can create two functions to solve this problem:

  • create a circle function
  • color function

Dividing complex problem into small components makes program easy to understand and use.

Types of functions in C programming

Depending on whether a function is defined by the user or already included in C compilers, there are two types of functions in C programming

There are two types of functions in C programming:


Standard library functions

The standard library functions are in-built functions in C programming to handle tasks such as mathematical computations, I/O processing, string handling etc.

These functions are defined in the header file. When you include the header file, these functions are available for use. For example:

The printf() is a standard library function to send formatted output to the screen (display output on the screen). This function is defined in "stdio.h" header file.

There are other numerous library functions defined under "stdio.h", such as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions are available for use.

Visit this page to learn more about standard library functions in C programming.


User-defined functions

As mentioned earlier, C language allows programmer to define functions. Such functions created by the user are called user-defined functions.

Depending upon the complexity and requirement of the program, you can create as many user-defined functions as you want.

How user-defined function works?

#include <stdio.h>
void functionName()
{
    ... .. ...
    ... .. ...
}

int main()
{
    ... .. ...
    ... .. ...

    functionName();
    
    ... .. ...
    ... .. ...
}

The execution of a C program begins from the main() function.

When the compiler encounters functionName(); inside the main function, control of the program jumps to

 void functionName()

And, the compiler starts executing the codes inside the user-defined function.

The control of the program jumps to statement next to functionName(); once all the codes inside the function definition are executed.

How function works in C programming?

Remember, function name is an identifier and should be unique.

Advantages of user-defined function

  1. The program will be easier to understand, maintain and debug.
  2. Reusable codes that can be used in other programs
  3. A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.