Introduction to Function in C

A function is a block of code that performs a specific task. For example, the main is function and every program execution starts from main function in C programming.

The C program is made of one or more functions. Every program must have at least one function with the name main. The execution of the program always starts from main function and ends with main function. Main function can call other functions to do some special task.

The function is a small program is used to do a particular task. In C a big program divided into several small subroutines/functions/procedures. Hence C is a function-oriented programming language.

Types of functions

C supports two types of functions.

  1. Standard Library functions
  2. User-defined functions

Standard Library function in C

The Standard Library functions are inbuilt or pre-defined functions in C programming language. There are some problems which are common to all programmer like displaying characters to the screen, taking input from the end-user, finding square root values of a number. For the solution of these common problems some pre-defined functions already given. These pre-defined functions were written by the creator of the C language. These functions are defined in the header file. When we include a header file in our program than all the functions available in that header file are assessable.

Examples of standard library function in C

For example, stdio.h is a header file, which has many predefined functions for input-output processing like printf(), scanf(), gets(), puts(), fprintf(), fputs(), fgets() e.t.c. When we include stdio.h in our program using the statement #include<stdio.h> then all these functions are available for our program and we can use them in our program.

In math.h header file many pre-defined functions are available for mathematical computations like sqrt() for calculate the square root, pow() for calculate the power, cos() for calculate the cosine of angle in radians, sin(), tan(), acos(), atan(), cosh(), floor() e.t.c.

Below program calculate the square root of a given number using the mathematical library function sqrt().

The square root of a given number using sqrt()

#include<stdio.h>
#include<math.h>
int main()
{
   int num;
   printf("Enter an integer number: ");
   scanf("%d", &num);
   float square = sqrt(num);
   printf("Square root value of %d = %.2f\n", num, square);
   return 0;
}

Output:-

Enter an integer number: 25
Square root value of 25 = 5.00

Enter an integer number: 10
Square root value of 10 = 3.16

Power of a Number using pow()

#include<stdio.h>
#include<math.h>
int main()
{
   int base, power;
   long result;
   printf("Enter base and power values: ");
   scanf("%d %d", &base, &power);
   result = pow(base, power);
   printf("Result = %ld\n", result);
   return 0;
}

Output:-

Enter base and power values: 2 3
Result = 8

Enter base and power values: 5 2
Result = 25

User-defined function in C

In addition to standard library functions supplied by the system, C allows programmers to write their own functions for a specific work to accomplish. A function defined by the user to accomplish a task is called a user-defined function. The below program calculates the power of a number using user-defined function power().

#include<stdio.h>
long calculatepower(int a, int b);
int main()
{
   int base, power;
   long result;
   printf("Enter base and power values: ");
   scanf("%d %d", &base, &power);
   result = calculatepower(base, power);
   printf("Result = %ld\n", result);
   return 0;
}

//function for calculate the power of a number
long calculatepower(int a, int b)
{
   long result=1;
   for(int i=b; i>=1; i--)
   {
     result *= a;
   }
   return result;
}

Output:-

Enter base and power values: 5 2
Result = 25

Enter base and power values: 7 3
Result = 343

In this program, we defined our own function to calculate the power of a number, so no need to include the math.h header file because we are not using any math.h related functions.

The below program will demonstrate the addition of two numbers using the user-defined function sum.

#include<stdio.h>
int sum(int a, int b);
int main()
{
   int a = 10, b = 20;
   int result = sum(a,b);
   printf("Result = %d\n", result);
   return 0;
}

int sum(int a, int b)
{
   int sum;
   sum = a+b;
   return sum;
}

Output:-

Result = 30

The function from where any function is called is termed as caller function, and the function which is called by any function is termed as called function. For example, In the above program main a caller function and sum is a called function.

How the user-defined function executed in C

In C program execution always starts from the main function. When the compiler encounters any function inside the main function then control goes to called function. Now, the compiler starts executing the codes inside the called function. After completion of the execution of called function, control came back to the main function and all remaining codes of the main function executed.

Special points on execution of the user-defined function

1) If we define a function but not called in any function then that function will not be executed. Function is only executed when it is called by any function.

#include<stdio.h>
void display();
int main()
{
   printf("Function sum() is not called.\n");
   return 0;
}
void display()
{
   printf("This line is displayed from the function display()");
}

Output:-

Function sum() is not called.

In the above program, the function display is not called in main function, so the function display() is not executed. If you have doubts then write one another program, call the display() function from main function, compile and execute it. Observe the output of the program.

#include<stdio.h>
void display();
int main()
{
   printf("This time function sum() is called.\n");

   //function calling
   display();
   
   return 0;
}
void display()
{
   printf("This line is displayed from the function display()");
}

Output:-

This time function sum() is called.
This line is displayed from the function display()

2) We can write many functions in a program and it is not compulsory that function should be called only from the main function. We can call a function from any function of the program. The function can be called from itself. A function which calls itself is called recursive function, we will discuss it later first you should learn the basics of function. You can find it here:- Recursion in C.

#include<stdio.h>
void display();
void show();
int main()
{
   printf("Execution of main() function started.\n");
   printf("Function display() is called from main() function.\n");
   display();
   printf("Execution of main() function Ended.\n");
   return 0;
}

void display()
{
   printf("\nExecution of display() function started.\n");
   printf("Function show() is called from display() function.\n");
   show();
   printf("Execution of display() function ended.\n");
}

void show()
{
   printf("\nExecution of show() function started.\n");
   printf("Execution of show() function ended.\n");
}

Output:-

Execution of main() function started.
Function display() is called from main() function.

Execution of display() function started.
Function show() is called from display() function.

Execution of show() function started.
Execution of show() function ended.
Execution of display() function ended.
Execution of main() function ended.

Why execution always starts from main function in the C language, not from any other function?

The main is also a user-defined function with predefined characteristic, execution always starts from main function. The functions are defined by the user. Different users/programmers may write different functions in a program. Which program will be executed first and which will in last, it will be a big problem for the programmers. For the solution of this problem, C developers written language such a way that execution always starts from main function and other user-defined functions should be called from main function. The C compiler is a program or tool which have code to perform the checking syntax error and later execution start from the main method.

Advantage of user-defined function in C

There are several advantages of function in C or any other programming language.

1) Modularity:- Dividing a big program into small modules. Using functions, the problem can be divided into small understandable and manageable steps.

2) Reusability:- Write once, use many times. Functions avoid repeating code in a program. One function can be called and used in several places. For example printf function, the printf function is defined only one time in stdio.h header file, but we use it many times in our program.

3) Simplicity:- Easy to read instructions. Using functions our program becomes very simple and understandable.

4) Efficiency:- Program performance increased. Usage of functions reduces the amount of work and development time. Using function we can easily find the errors in our program.

Another benefit of using the function is different programmers working on one large project can divide the workload by writing different functions. Functions can be used to protect data. This is related to the concept of local data. Local data is the data described within a function. They are available only within a function when the function is being executed.

Structure of a function in C programming

A function may have a declaration, calling, definition and return statement. We will discuss them one by one. The below program shows the structure of a function.

#include<stdio.h>
int sum(int a, int b); //function declaration
int main()
{
   int x = 10, y = 20;
   int result = sum(x,y); //function calling
   printf("Result = %d\n", result);
   return 0;
}
//function definition
int sum(int a, int b) 
{
   int sum;
   sum = a+b;
   return sum; //return statement
}

Function definition

The collection of program statements (code) in C that describes the specific tsk done by the function is called a function definition. The function definition consists of code for the function. The definition creates the actual function in memory. Syntax of function:-

return-type function-name (parameters list)
{
   //code or logic for function
   return(expression);
}

Below is the example of a function definition

int sum(int a, int b) //function header
{ 
   //function body
   int sum; 
   sum = a+b;
   return sum; //return statement
}

A function definition consists of two parts,

  1. Function header part
  2. Function body part

Header part of a function

In C, the function header consists of three parts: the return-type, the function-name, and the parameter list. The function header is not terminated by a semicolon.

The return-type specifier is the type of data that the function is excepted to return to its calling function. For example in the function sum is calculating the sum of two int numbers, and returning the result. The sum of two int data types will be also an int data type so the return-type of function sum is int.

In the absence of any data type, the type int is assumed by default. The data type void may be used for the return type of the function which does not return any value.

The return-type specifier is followed by a function-name. The function-name may be any valid C identifier.

The parameter list defines and declares the variables that will contain the data received by the function from the calling function. The multiple parameters must be separated with commas. If the function has no parameters then it can be declared with keyword void or leave empty.

The function display() without any parameters

include&stdio.h>
void display(); //function declaration
int main()
{
   display(); //function calling
   return 0;
}
void display() //function definition
{
   printf("Hello");
}

The function display() with parameter void

void display(void)
{
   printf("Hello");
}

The body part of a function

The function body contains the local declarations and the function statements enclosed within a pair of curly braces. The body starts with the local definitions that specify the variables needed by the function. After the local definitions, the function statements, terminating with the return statement, are coded. If a function return type is void, it can be written without a return statement.

Function Calling

When a function is called then control passes to that of the called function. Once the execution of function completed then the control returned back to the caller function. Generally, a function will process information passed to it from the calling statement of a program and return a single value. A function with a returned type void does not return any value. It only returns the control from called function to calling function. Syntax:-

If arguments to be passed to the function then the calling statement would be:
Function with return type void
function-name(variable1, variable2, ……..);
Function return any value
variable-name = function-name(variable1, variable2, ……..);

If there are no arguments to be passed to the function,
Function with return type void
function-name();
Function return any value
variable-name = function-name();

Difference between arguments and parameters

Information passed to the function via special identifiers or expression called arguments. The variables that are declared in the header of the function definition are called parameters. Sometimes arguments and parameters are also called actual parameters and formal parameters respectively.

#include<stdio.h>
int sum(int x, int y);
int main()
{
   int a = 10, b = 20;
   int result = sum(a,b);
   printf("Result = %d\n", result);
   return 0;
}
int sum(int x, int y) 
{
   int sum;
   sum = x+y;
   return sum;
}

In this program, the variable a and b are arguments and the variables x and y are parameters. Note:- arguments are the variables in the caller statement and parameters are the variables in the called function.

The parameters of the called function are declared local and it gets initialized with the values of the arguments. In the above program, the function is called with arguments (values of the variable) a and b. So, parameters x and y initialized with values of arguments x and y respectively. Hence x holds 10 and y holds 20.

Rules for parameters

There are certain rules for parameters that must be kept in mind while writing a C program that uses one or more functions. These are listed below:
1) The number of parameters must be the same as the number of arguments.
2) Parameter association in C is positional. This means that the first parameter corresponds to the first argument and the second matches the second and so on.
3) Parameters and arguments must be of compatible data types.
4) Argument may be a variable, constant, or any expression matching the type of corresponding formal parameters.
5) The name of the parameters can be the same as the name of the arguments.

#include<stdio.h>
void add(int a, int b);
int main()
{
   int a = 5, b = 10;
   add(a,b);//variable arguments
   add(1,2);//constant arguments
   return 0;
}
void add(int a, int b)
{
   printf("Sum = %d\n",a+b);
}

Output:-

Sum = 15
Sum = 3

Function declaration or function prototype in C

In a C program, a user-written should normally be declared prior to its use to allow the compiler to perform type checking on the arguments used in its call statement. Function declaration consists of only function header, they don’t contain any code/logic. Like function definition headers, function declaration also consists of three parts: the return-type, the function-name, and the parameter list. Function declaration always terminated with a semicolon. Syntax:-

return-type function-name (data-type arg1, data-type arg2, …);
or,
return-type function-name (data-type list);

There are two ways for prototyping functions. The most common method is simply to write the function declaration with the type of arguments, with or without identifiers for each. The ANSI standard does not require variable names for the prototype declaration parameters. In fact, readability and understandability are improved if names are used.

void add(int a, int b);
void add(int, int);
Both are valid function declaration. We can use anyone.

Why function declaration?

Before using the function the compiler must know about the number of parameters and type of parameters that the function expects to receive and the data types of the value that it will return to the calling program. Placing the function declaration statement prior to it enables the compiler to check on the arguments used while calling that function.

The declaration is placed in the global declaration section before main function. Grouping all function declarations at the beginning of the program makes them available whenever they are needed. Function declarations also provide an excellent quick reference for the functions used in the program, making them excellent documentation.

Special points on the function declaration

1) The names do not need to be the same in the function declaration and the function definition. But data-type should be the same else we will get a compile-time error. For example,

#include<stdio.h>
void add(int x, int y);
int main()
{
   add(1,2);
   return 0;
}
void add(int a, int b)
{
   printf("Sum = %d\n",a+b);
}

In this program, for the add() function all below function declaration are valid. The name can be different.
void add(int a, int b);
void add(int firstNumber, int secondNumber);
void add(int x, int y);

For the add function, the below function declaration gives the compile-time error because their data-types are different.
void add(int x, float y); //invalid
void add(float x, int y); //invalid
void add(); //invalid
void add(int y); //invalid

2) The function declaration is optional when the function is declared, before the main function. C program executes from top to bottom, so from top compiler start checking. A function declaration tells the compiler that somewhere in the program there is a function of this name and data-type. Then the compiler encounters the main function, and when the function is called then control goes to that function. But if we declare a function before the main function then compiler check it before the main function. When compiler encounter function call in the main function at that time compiler already knows that there is a function having this name and return-type. So, the function declaration is optional time.

#include<stdio.h>
void add(int a, int b)
{
   printf("Sum = %d\n",a+b);
}
int main()
{
   add(1,2);
   return 0;
}

Output:-

Sum = 3

In this program, the function is declared before the main function so we don’t use the function declaration part.

Return statement of a function in C

Return statement has two important uses:
1) It causes an immediate exit from the function that it is in. That is, it caused program execution to return to the calling code.
2) It may be used to return a value.

Syntax:-

  1. return(expression); or return expression;
  2. return;

Example:-
return;
return 5;
return a;

Special points on the return statement

1) If a function returns a value usually it has to be assigned to some variable since a value is being returned. In the below program the function multiply() returns the int value, to store the int value one variable result is declared.

#include<stdio.h>
int multiply(int a, int b)
{
   return a*b;
}
int main()
{
   int result = multiply(5,2);
   printf("Multiplication result = %d\n",result);
   return 0;
}

Output:-

Multiplication result = 10

2) If there is no assignment specified, then it is also a valid statement. But we will get a warning message. For example in the below program we didn’t store the returned value in any variable so, finally returned value is discarded. From this program, we get the output as a garbage value.

#include<stdio.h>
int multiply(int a, int b)
{
   return a*b;
}
int main()
{
   int result;
   multiply(5,2);
   printf("Multiplation result = %d\n",result);
   return 0;
}

3) If the type of return value has been specified as void, then no need to give any return statement in the function. Or, we can give the return statement, it may be written simply as:- return; There must be no expression appearing in the return statement.

#include<stdio.h>
void display()
{
   printf("Hello");
}
int main()
{
   display();
   return 0;
}

4) A function can only return one value. (To return more than one value we need to use pointer concept, array and strings are implicit pointers, it will be discussed later.) There may be more than one return statement in a function, but only one return statement will be executed per call to the function.

#include<stdio.h>
int checkOddEven(int a)
{
   if(a%2==0) return 1;
   else return 0;
}
int main()
{
   int result = checkOddEven(5);
   printf("Result = %d\n",result);
   result = checkOddEven(10);
   printf("Result = %d\n",result);
   return 0;
}

Output:-

Result = 0
Result = 1

In this program one function is used to check the number is odd or even. This function has two return statements. If the number is even then it will return 1 means true else it will return 0 means false. The integer number 5 is odd so we get 0 for the first call and 10 is even so we get 1 for the second call to the function.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply