Unlock the complete
Logicmojo experience for FREE

1 Million +

Strong Tech Community

500 +

Questions to Practice

50 +

Jobs Referrals

Logicmojo - Updated April 10, 2023



Introduction

We already have int, char, float, and double data types defined in C to hold integers, characters, and decimal values.(also known as the primitive data types). We also have some derived data types, such as arrays and strings, to store elements of comparable data types together. Arrays and strings, on the other hand, can only store variables of comparable data types, whereas strings can only store characters. What if we need to store two distinct data types in C together for a large number of objects? For example, a pupil variable may have a name, class, section, and so on.

Functions are just sections of code that are defined to execute a certain task. In this way, dividing a large program into functions, each of which performs a much simpler task, simplifies coding and improves readability. The best part about functions is that they can be reused throughout the program whenever necessary. This also aids in the reduction of repetitive code in our program.

When we have a large task to perform, it appears to be better to divide the task into sections and complete the parts independently. This manner, it appears less complicated and ends sooner. We'd like to do the same with our code. A complex code can be simplified by dividing it into pieces, each of which performs a distinct duty in the code.

In this article, we'll look at what it means and how it works.


What is Function in C ?

Functions are collections of statements that accept input, conduct operations, and return results. A function's operation occurs only when it is called. Rather than writing the same code for different inputs over and over, we can call the function instead of writing the same code.


Functions In C

Application of the Function in C

C program can be simply divided into multiple independent functions. It is entirely up to us how we divide our available code into different available functions. However, the division should be done logically such that each function is capable of executing a certain task.

The function declaration informs the compiler about the function's name, parameters, and return type. In other words, the function definition aids in the provision of the real body of any function that we desire in a code.

Syntax of Function In C

In the C programming language, we use the following syntax to create a function:

return_type function_name( parameter1, parameter2 ) {
   //body of the function
}                  

C programming functions are classified into three categories:

  1. Function Declaration

  2. Function Definition

  3. Function Calling

Function Declaration In C

The term "function declaration" refers to the act of writing the name of a programme. It is a required component for using functions in programming. A function declaration is similar to a variable declaration in that it just specifies the name of a function that will be used in our program. A function cannot be used before it is declared in a program. A function declaration is frequently referred to as a "function prototype."

Parts Of Function Declaration

return_type function_name( parameter_1, parameter_2 )                   

Function Return Type

The function return type specifies the type of value returned after all functions have been executed. Following the execution of statements within the function, it will return an integer value.

int rect(int length, int breath)                  

Function Parameter

The function return type specifies the type of value returned after all functions have been executed. Following the execution of statements within the function, it will return an integer value.

int rect(int , int )                  

Function Definition In C


Functions In C

Defining a function entails specifying the function's body. This is the code that will be run each time the function is invoked.

return_type function_name( parameter list ) {
   //body of the function
}                  

In the C programming language, a function definition consists of a function body and a function header. Let's take a look at all of the components that make up a function:

  1. Return Type :-

    A value can be returned by a function. The data type of the value returned by the function is specified by return_type. Some functions carry out the intended activities but do not return a value. The keyword void is used as the return_type in this instance.

  2. Function Name :-

    This is the function's official name. The function signature is made up of the function name and the argument list.

  3. Parameters :-

    A parameter is similar to a void. When you call a function, you pass a value to the parameter. This value is known as the real parameter or argument. The type, order, and number of parameters of a function are referred to as the parameter list. Parameters are optional; a function may have no parameters. The function body is made up of statements that describe what the function does.

  4. Function Body :-

    The function body is made up of statements that describe what the function does.

Function Calling In C

A function call, as the name implies, is a request to the compiler to execute a function. The function can be called at any time in the program. The only thing to remember is that you must pass as many arguments of the same data type as specified when you declared the function. If the function parameter does not change, the compiler will run the program and return the result.

Syntax

function_name(parameter_1, parameter_2);

Here, p1 and p2 are the parameters mentioned previously during the function's declaration. All of the code inside the function that we described earlier will be performed by this single line.

It should be noted that when calling a given function, the same amount of parameters as in the declaration should be provided as input. Furthermore, these parameters must have the same data type as the declaration.

<

Example to Understand all three categories for Function In C

#include <stdio.h>

// function declaration
int addNumbers(int a, int b);

int main() {
   int num1 = 5, num2 = 10, sum;

   // function call
   sum = addNumbers(num1, num2);

   printf("Sum of %d and %d is %d", num1, num2, sum);
   return 0;
}

// function definition
int addNumbers(int a, int b) {
   int result = a + b;
   return result;
}
                  

In this example, we defined the function "addNumbers", which accepts two integer inputs a and b and returns their sum. With the parameters num1 and num2, the main function calls this addNumbers function and stores the result in the variable sum.

The addNumbers function comes after the main function and is preceded by a function declaration that provides the function name, return type, and parameter list. The code that conducts the addition operation and returns the result to the calling function is included in the function specification.

When the addNumbers function is called up, the values of num1 and num2 are supplied as arguments to the function. The function adds these numbers together and returns the result to the caller function. The main function then prints the sum of num1 and num2 to the console using the returned result.





Learn More

Function Arguments

The variables that happen to accept the values of the arguments must be declared whenever a function wants to use them. These variables are referred to as the formal parameters of the supplied function.

The formal parameters behave in the same way as any other local variable within our supplied function. When they enter a function, these arguments are formed. It is then destroyed when it exits.

There are two ways to deliver these arguments to a particular function during the calling of that function:



Type of Call Description of Call Type
Call By Reference The Call by Reference technique inserts a formal copy of the address of the provided argument into the parameter. The use of address within this function aids in retrieving the actual parameter used in this call. It signifies that any modifications made to the parameter will have an effect on the provided argument.
Call By Value The Call by Value method generates a duplicate of the real value of the given argument in the formal parameter of the function. The modifications that occur on the parameter (which occurs within the function) have no influence on the available argument.




C programming uses Call by Value by default for supplying arguments. In general, this means that we cannot utilise the code contained within a function to change the inputs used to call the function.

Various Methods of Calling a Function

There are four main aspects of C function calls depending on whether the function accepts parameters and returns a value. These include:

  1. Function with no arguments and with return value

  2. Function with argument and with no return value

  3. Function with arguments and with return value

  4. Function with no arguments and no return value

How the Function in C Works?


Functions In C

When the compiler sees a function call in the program, it transfers control to the function definition block with the specified parameters; whether user-defined or standard library functions, their operation is the same.

The C function's operation can be divided into the following steps, which are listed below:

  1. Declaring a function :

    This is the phase when we define a function. The function's return types and parameters are defined here.

  2. Calling the function :

    This is the stage in which we call the function by giving the arguments in the function.

  3. Executing the function :

    This is the step in which we run all of the statements included within the function to obtain the final result.

  4. Returning a value :

    This is the stage in which the calculated value following the function's execution is returned.

  5. Exiting the function :

    This is the final step in which all allocated memory to variables, functions, and so on is deleted before giving full control to the main function.

When a program begins to operate, the compiler runs the code in the main() function line by line. When it comes across a function call in a certain line, it passes control to the function definition. Aside from that, the compiler records the address of this line, known as the return address, so that after the function is finished, we can return to it.

When we reach the end of the function, control is transferred back to the line from where the function was called, and the code resumes normal execution.

Types of Functions in C

Members of a structure in C can be accessed and given values in a variety of ways. Structure members have no significance apart from the structure. To give a value to any structure member, the member name must be linked with the structure variable via the dot(.) operator, also known as the period or member access operator.

  1. 1 . User Defined functions

  2. 2 . Standard Library Functions


Functions In C

User Defined Functions in C

These are the functions that are declared, defined, and called by a programmer or user in a program. The flexibility to define and use any function boosts the reach, functionality, and reuse of C programming. The ability to add a user-defined to any library and use it in other programmes is a key benefit of C programming.


Example

#include <stdio.h>
 
int sum(int a, int b)
{
  return a + b;
}
 
// Driver code
int main()
{
  int a = 5, b = 6;
  
  // function call
  int ans = sum(a, b);
 
  printf("Sum of the number is: %d", ans);
  return 0;
}          

Output

Sum of the number is : 11                 

The compiler in the above code begins at the beginning of the main method. When it sees a function call, it moves control to the location where the function was defined. As a result, the code included within the brackets in the function definition is executed. As a result, when the function is called in this scenario, the compiler proceeds to where the function was defined and computes the sum.

When the compiler reaches the function's return statement, it returns control to where it was left in the main method. So, in the main method, the returned integer is saved in the ans variable, and the remaining code is executed normally.

Advantages of user-defined function

  1. The program will be simpler to comprehend, maintain, and debug.

  2. Codes that can be reused in other programs

  3. Large programs can be broken down into smaller components. As a result, a huge project might be distributed among several programmers.

Standard Library Functions

A library function is often known as a "built-in function." There is already a compiler package that contains these functions, each of which has a defined meaning and is included in the package. Built-in functions have the advantage of being immediately useable without the need for definition, whereas user-written functions must be declared and defined before they can be used.

The table below contains a list of the most commonly used header files.



Header fileDescription
stdio.hThis is a standard input/output header file. It contains all the library functions regarding standard input/output.
conio.hThis is a console input/output header file.
string.hIt contains all string related library functions like gets(), puts(),etc.
stdlib.hThis header file contains all the general library functions like malloc(), calloc(), exit(), etc.
math.hThis header file contains all the math operations related functions like sqrt(), pow(), etc.
time.hThis header file contains all the time-related functions.
ctype.hThis header file contains all character handling functions.
stdarg.hVariable argument functions are defined in this header file.
signal.hAll the signal handling functions are defined in this header file.
setjmp.hThis file contains all the jump functions.
locale.hThis file contains locale functions.
errno.hThis file contains error handling functions.
assert.hThis file contains diagnostics functions.


Advantages of Library function in C

  1. C Library functions are simple to use and optimised for speed.

  2. C library functions save a significant amount of time, i.e. function development time.

  3. C library functions are useful because they always work.

Main Function in C

You've probably seen the main() function declared in every piece of C code. This is due to the fact that the main() function is the most significant component of any C program. When we run a program, the code begins to execute in the main() function. As a result, any C program must include a main() function. This is where the compiler will begin running the code, and when the main() function terminates, the program will likewise terminate. As a result, this is the beginning and finish of any C program.

Syntax

int main(){

… //code body

return 0;

}

The main() function's return type is normally int, although it can alternatively be void. We don't need to return anything at the end of the main() function if the return type is void, so we just type return.

When using the int return type, we must return an integer at the end of the function, which is normally 0. The main() method is the beginning and finish of a C program, thus if it is executed without problems, the entire program is also error-free. As a result, if our main() method returns 0, it means that the entire program was executed without faults.

Recursive Functions in C

Another form of function is recursive. Recursive functions are ones that call on themselves. This signifies that there is a call to themself again in the definition of a recursive function, but with different parameters.

You would suppose that if the function kept calling itself in this manner, it would enter an infinite loop. To circumvent this, recursive functions contain a terminating condition, often known as the base case, before it calls itself again. As a result, once the condition is met, the function does not call itself again and so terminates.

To be more specific, a recursive function will call itself with parameters that will take it to the termination condition; otherwise, the program will run in an indefinite loop until memory is exhausted.

Lets see how the recursive function works :


Functions In C

Consider the factorial of the following number: 5! =5 * 4 * 3 * 2 * 1. This is accomplished by constantly calculating fact * (fact -1) until fact equals 1.

Example

#include<stdio.h>

int factorial_01(int n)
{
    if(n == 0)
        return 1;
    else
        return (factorial_01(n-1)*n);
}

int main()
{
    int a fact;
    
    printf("Enter a number : ");
    scanf("%d",&a);
    
    fact = factorial_01(a);
    
    printf("The Factorial of %d = %d",a,fact);
    return 0;
}



Output

Enter a number : 5
The Factorial of 5 = 120

In the preceding program, we compute the factorial using recursion in C. Here we declare the variable n, which holds the integer whose factorial needs to be calculated.

The factorial_01 function computes the factorial of that number. If the value of n is 0, the factorial_01 function returns 1, which is the function's base condition. Otherwise, factorial(n-1) is computed recursively and then multiplied by n. The factorial number is contained within the fact that we finally print.

Observe the picture below to better understand the recursive method, which consists of executing the function itself until the base case or halting condition is achieved, and then collecting the prior values:


Functions In C

Inline Functions In C

In C programming, functions are used to store the most frequently used instructions. It is employed in the modularization of the program. The instruction pointer moves to the function definition whenever a function is invoked. Following the execution of a function, the instruction pointer returns to the statement from where it jumped to the function declaration.

We need an extra pointer head to move to the function definition and return to the statement whenever we use functions. We employ inline functions to obviate the necessity for such pointer heads.

A function call is directly substituted with actual program code in an inline function. Because all actions are performed within the inline function, it does not jump to any blocks.


Functions In C

Inline functions are typically used for quick calculations. They are unsuitable for large-scale computing. An inline function is similar to a regular function except that the keyword inline appears before the function name. The following syntax is used to define inline functions:

Syntax

inline return_type function_name (parameter list){

    //function body
    
    return value;
}
             


for Example

inline int add(int x, int y) {
    return x + y;
}

When you call an inline function, the compiler replaces the function call with the function body, as shown below:

Output

int result = add(10, 20);
// This line is replaced with:
int result = 10 + 20;

Inline functions work well for short, often called functions. It is crucial to note, however, that the decision to inline a function is ultimately up to the compiler, and in some situations, the compiler may opt not to inline a function even if it is designated as "inline."

Important Considerations for Functions in C

  1. Every C program has a function. You must utilise the main function even if you do not use a library or a user-defined function. The main function serves as the program's entry point because it is where the compiler begins running the code.

  2. A function has a return type even if it does not return a value. If a return value is specified, the return type is the value's data type. However, if there is no return value, the function's return type is void.

  3. C functions are unable to return arrays or function types. However, by using pointers, you may easily avoid this limitation.

  4. While void func() and void func(void) have the same meaning in C++, this is not the case in C programming. A function declared in C that does not have a parameter list can be invoked with any number of parameters. If you want to call a function without passing any parameters, it is best to declare it as void func(void) rather than void func().

  5. If you call a function before declaring it, the C compiler will assume that the return type is int by default and will throw an error if the data type of the return value is anything other than int.


Advantages of Functions in C

Functions in C is a very useful element of C that has numerous advantages, as listed below:

  1. The function can help to limit the number of times the same statements appear in the program.

  2. The method improves the readability of code.

  3. There is no limit on the number of times a calling function can be invoked.

  4. The function shrinks the program's size.

  5. Once the function is declared, you can use it without worrying about how it works inside.



Conclusions

You've learnt everything there is to know about functions in C programming in this article. A C program's basic building elements are functions. They offer the benefits of reusability, modularity, and simplicity. As a result, learning how to develop and use functions is critical for optimising your program.

The main() function is a unique type of function that is required in every C program, and it is where the code begins to execute. We got to know about recursive functions, or functions that call themselves. We also looked at the inline function, which will have all of the code put inside it pasted into the main() method and then performed.

Good luck and happy learning!