Functions in C

What are the Functions of C Language?

The function is a piece of code that performs a specific task. We have already studied structures. In structure, we studied that structure is a group of related data members. Now, the function is a group of related instructions that perform a specific task. So, grouping data members is a structure, and grouping instructions is a function.

Functions are also called modules or procedures. Instead of writing a single main program i.e. writing everything inside the main function, we can break the main function into small manageable size pieces and we can separate the repeating tasks or smaller tasks as a function.

For Example;

If we write one program, and if we put everything inside the main function, then such type of programming approach is called Monolithic programming. If your main function contains thousands of lines of code, then it is becoming very difficult to manage. This is actually not a good programming approach.

Functions | Why should we learn Functions

So, if we broke the program into smaller tasks, i.e. into many smaller functions and each function performs a specific task, then such type of programming is called “modular programming” or “procedural programming” and this approach is good for development.

modular programming or procedural programming

As shown in the above image, the first function i.e. function1() will perform some specific task and another function i.e. function2() will perform some other task, and similarly, function3() may perform some task. So, in this way, we can break the larger task into smaller simple tasks, and then we can use them all together inside the main function.

Here, in the Modular Programming Approach, you can break the program into smaller tasks and you can focus on smaller tasks and finish them and make them perfect. It is easy for one single individual to develop the application even if you can break this software project into a team of programmers where each programmer will focus on one or many smaller tasks.

This Modular style of programming approach has increased productivity and also reusability. For example, if you want the logic of function2 three times inside the main method, then you simply need to call function2 three times. That means we are reusing the logic defined in function 2. This is called reusability.

The same function can also be used in other software projects also. You can put the group of functions together in a library. These are the benefits of functions.

C language is a procedural or modular programming language and this is the topmost feature supported by C programming which is also there in C++. Beyond this one, C++ follows object orientation where you group the related data members and functions together and put them in a single class.

Modular Programming Examples:

Now, let us focus on modular programming and let us see how we can break a program into functions. Let us write a simple program using a function and learn how we can separate the task from the main function.

Program: Adding Two Numbers

In the below example, we have implemented the logic to add two numbers inside the main function only.

#include <stdio.h>
int main ()
{
    int x, y;
    x = 10;
    y = 5;
    int z = x + y;
    printf ("sum is %d", z);
}

As you can see in the above code, first we declare two variables x and y and then we initialize these two variables with values 10 and 5 respectively. Then we add two variables and store the result in another variable i.e. z and finally print the value of z in the console and that is what you can see in the output.

Let us see how to write the same Program using Function. For a better understanding please have a look at the below image.

Modular Programming Examples

As you can see in the above image, we created a function called add which takes two input parameters a and b of type integer. This add function adds the two integer numbers it received as input parameters and stores the result in variable c and returns that result.

Now see the main function. From the main function, we are calling the add function and while calling the add function we are passing two parameters i.e. x and y (actually we are passing the values stored in x and y) and these parameters’ values will go into a and b. The add function then adds these two values and returns the result to the calling function (the function is called the add method) i.e. the main method. The main method then store the result coming from the add method into the variable z and then print the result on the output window.

The complete code is given below.
#include <stdio.h>
int add (int a, int b)
{
    int c;
    c = a + b;
    return (c);
}
int main ()
{
    int x, y;
    x = 10;
    y = 5;
    int z = add (x, y);
    printf ("sum is %d", z);
}

Different Parts of a Function:

To understand the different parts of a function, please have a look at the below image.

Different Parts of a Function
What are the Parameters of a function?

For a better understanding of the function parameters, please have a look at the below image.

What are the Parameters of a function?

As you can see in the above image, we are passing two values x and y to the add function which is taking two parameters (a and b). The parameters (x and y) which are passing to the add function are called Actual Parameters. The parameters (a and b) which are taken by the add method are called Formal Parameters. When we call the add method the values of actual parameters are copied to the formal parameters. So, x value i.e. 10 is copied to a, and y value i.e. 5 is copied to b.

How does it work inside the main memory?

When the program starts i.e. when the main method starts its execution, three variables (x, y, and z) are declared inside the stack, that is inside the activation area of the main function. Then the x and y are assigned with values 10 and 15 respectively. And then the main method calls the add method. Once the add method is called, its own activation area is created inside the stack and it will have its own variables i.e. variables a, b, and c are created inside this activation area. Then the value of x i.e. 10 and the value of y i.e. 5 passed to add function are copied to the variable a and b respectively. Then the add method adds the two numbers and the result is 15 which is stored in the variable c and that result i.e. 15 is returned from the add method. That result coming from the add method is stored in the variable z and that will be printed in the console window. For better understanding, please have a look at the following image.

How does it work inside the main memory?

So, this is what happens inside the main memory when we are writing functions. One more point you need to remember is, that one function cannot access the variables of other functions. I hope you understand the basics of Functions in the C Program. Now let us proceed and understand the function in detail with more examples.

What are Functions in C Language?

A self-content block of 1 or more statements or a subprogram that is designed for a particular task is called a function. In C, the idea of top-design is done using functions. A-C Program is made of one or more functions, one of which must be named as the main. The execution of the program always starts and ends with the main, but it can call other functions to do special tasks.

A function in C is a self-contained program segment that carries out some specific, well-defined task. If a program contains multiple functions, their definitions may appear in any order, though they must be independent of one other. That is, one function definition can’t be embedded within another.

A function will carry out its intended action whenever it is called from some other portion (called calling function) of the program. Once the function (called function) has carried out its intended action, control will be returned to the point from which the function was called.

Generally, a function will process information passed to it from the calling portion of the program, and return a single value. Information will be passed to the function via special identifiers called arguments also called parameters and returned via the return statement.

Types of Functions in C Langauge:

There are two types of functions in C Programming Language. They are as follows:

  1. Standard library functions
  2. User-defined functions
Types of Functions in C Language
Function Syntax in C Language:
Function Syntax in C Language
Different Parts of a Function in C Language:
  1. Return Type: Function returning the value in which data type. It can be void if the function returns nothing
  2. Name of the function: It is the identifier for the function name.
  3. Arguments: Argument is the variables that the function will use. (can be void)
  4. Body: this is the main logic of the function.
  5. Return Statement: if the return type is not null then the function will return a variable according to the return type.

Note: Function does not have access to use the variables of other functions (even the main function). So if you want the function to use some variable of another function then you have passed that variable as an argument to the function.

Example to understand Functions in C Language:
#include <stdio.h>
void name(); /*function declaration */
void message(); /*function declaration */
void main()
{
    name();
    message();
}
void name() /*function definition */
{
    printf("Shishir ");
}
void message () /*function definition */
{
    name();
    printf("Hello ");
}

Output: Shishir Shishir Hello

In the above piece of code name() and message() are the user-defined functions. In the main(), name() and message() are the ‘called functions’ and main() is the ‘calling function’. In the message (), name() is the ‘called function’ and message() is the ‘calling function’. When the functions are called, they execute and perform their respective tasks.

Note: Even printf() that we use is a ‘called function’. It is an inbuilt function and can be used in our programs without worrying about defining it. Just don’t forget to use # include<stdio.h>.

Advantages of functions in C Language or Why do we need functions in C Language?
  1. Module Approach: By using the function we can develop the application in module format i.e. procedure-oriented language concept.
  2. Reusability: By using functions we can create re-usability blocks i.e. develop once and use multiple times.
  3. Code Maintenance: When we are developing the application by using functions, then it is easy to maintain code for future enhancement.
  4. Code Sharing: A function may be used by many other programs.
  5. Flexible Debugging: It is easy to locate and isolate a faulty function for further investigations.
  6. Data Protection: Functions can be used to protect data and local data. Local data is available only within a function when the function is being executed.
  7. Code Reduced: Reduces the size of the code, duplicate statements are replaced by function calls.
Standard Library Functions in C Language:

Library functions are a set of pre-implemented functions which are available along with the compiler. The implementation part of library functions is available in .lib or .obj files which are available in the C:\tc\LIB directory.

When we are working with pre-defined functions for avoiding the compilation error, we are required to go for forwarding declaration i.e. prototype is required. When we are required to provide a prototype of pre-defined functions, then required to go for header files. ‘.h files’ does not provide any implementation part of pre-defined functions, it provides only a prototype, i.e. forward declaration of functions. When we install C Software, some pre-defined functions automatically come with that in C: directory.

Example: puts(), gets(), printf(), scanf(), etc.

C Standard library functions or simply C Library functions are inbuilt functions in C programming. The prototype and data definitions of these functions are present in their respective header files. To use these functions we need to include the header file in our program.

Note: .lib or .obj files contains pre-compiled object code.

Example of Standard Library Functions in C Language:

If you want to use the printf() function, the header file <stdio.h> should be included.

#include <stdio.h>
int main()
{
    printf("Catch me if you can.");
}

If you try to use printf() without including the stdio.h header file, you will get an error.

Advantages of Using Standard Library functions in C Language:
  1. One of the most important reasons you should use library functions is simply because they work. These functions have gone through multiple rigorous testing and are easy to use.
  2. The functions are optimized for performance. Since, the functions are “standard library” functions, a dedicated group of developers constantly makes them better. In the process, they are able to create the most efficient code optimized for maximum performance.
  3. It saves considerable development time. Since the general functions like printing to a screen, calculating the square root, and many more are already written. You shouldn’t worry about creating them once again.
  4. The functions are portable, with ever-changing real-world needs, your application is expected to work every time, everywhere. And, these library functions help you in that they do the same thing on every computer.
Example to understand built-in C Library Functions:
#include <stdio.h>
#include <math.h>
int main()
{
    float num, root;
    printf("Enter a number: ");
    scanf("%f", &num);
    // Computes the square root of num and stores in root.
    root = sqrt(num);
    printf("Square root of %.2f = %.2f", num, root);
    return 0;
}

Output:
Example to understand built-in C Library Functions
What are the limitations of Pre-Defined Functions in C Language?

All pre-defined functions are contained limited tasks only i.e. for what purpose function is designed for the same purpose it should be used. As a programmer, we don’t have any controls on the pre-defined function implementation part as they are in a machine-readable format. In implementation whenever a predefined function is not supporting user requirements then go for a user-defined function.

User-Defined Functions in C Language:

User-defined functions are the functions that are created by the programmer so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code. C allows you to define functions according to your need. The function whose body is implemented by the developer or user is called a user-defined function.

As per client or project requirements, the functions we are developing are called user-defined functions. Always user-defined functions are client-specific functions or project-specific functions only. As a programmer, we are having full control of user-defined functions. As a programmer, it is possible to alter or modify the behavior of any user-defined functions if it is required because the coding part is available.

How does the user-defined function work in C Language?

In order to understand how the user-defined function works in C, please have a look at the following image.

How does the user-defined function work in C Language

The execution of a C program begins from the main() function. When the compiler encounters functionName(); the control of the program jumps to void functionName() definition And, the compiler starts executing the codes inside functionName(). The control of the program jumps back to the main() function once the code inside the function definition is executed.

Function Aspects:

There are three aspects of a C function.

  1. Function Declaration
  2. Function Call
  3. Function Definition
1. Function declaration:

The function declaration consists of only a function header and is terminated with a semicolon. The function declaration does not contain the body of the function. Like function definition headers, the function declaration header consists of three parts: the return type, the function name, and the formal parameters list. Unlike the header for the function definition, function declarations are terminated with a semicolon. The return type and the parameter list are required entries. If the function has multiple parameters, we separate each type-identifier with a comma otherwise simply write empty parentheses.

The C standard does not require identifier names for the function declaration’s formal parameters. For readability and understandability, we use identifiers in the declaration, however, the names do not need to be the same in the function declaration and the function definition. On the other hand, if the types are not the same, the compiler shows an error. The compiler checks the types in the function declaration with a function definition, the type must be matched or at least compatible.

The declaration is placed in the global declaration section before the main. 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 functions used in the program.

A function must be declared globally in a C program to tell the compiler about the function name, function parameters, and return type. The syntax is given below.

Syntax: return_type function_name (argument list);

Example to Understand User Defined Functions in C Language:
float sum(int, int);
main()
{
    float x;
    x=div(7,2);
    printf(“division=%f”,x);
}
float div(int a, int b)
{
    float c=(float)a/b;
    return (c);
}

The above example demonstrates, that the function declaration tells the program that a function named div, which accepts two integer values and returns a float value, will be called. The formal parameter names in the declaration do not need to be the same as the actual parameter names.

The actual body of the function can be defined separately. It’s also called Function Prototyping. The function declaration consists of 4 parts.

  1. Return type
  2. function name
  3. parameter list
  4. terminating semicolon
Return Type of a Function:

When a function is declared to perform some sort of calculation or any operation and is expected to provide some result at the end, in such cases, a return statement is added at the end of the function body. Return type specifies the type of value(int, float, char, double) that function is expected to return to the program which is called the function.

Note: In case your function doesn’t return any value, the return type would be void.

Function Name:

The function name is an identifier and it specifies the name of the function. The function name is any valid C identifier and therefore must follow the same naming rules as other variables in the C language.

Parameter List of a Function:

The parameter list declares the type and number of arguments that the function expects when it is called. Also, the parameters in the parameter list receive the argument values when the function is called. They are often referred to as formal parameters.

2. Function Call: 

The function can be called from anywhere in the program. The parameter list must not differ in function calling and a function declaration. We must pass the same number of functions as is declared in the function declaration.

Syntax: function_name (argument_list);

When a function is called, control of the program gets transferred to the function.

3. Function Definition: 

It contains the actual statements which are to be executed. It is the most important aspect to which the control comes when the function is called. Here, we must notice that only one value can be returned from the function. A Function definition has three principal components, they are function header, the argument declaration, and the body of the function.

Syntax:
return-type function-name(type arg1, type arg2,…..type agrn)
{
        Local variable declaration;
        Executable statements;
        Return statements;
}

The first line return_type function_name (argument list) is known as the function header and the statement(s) within curly braces is called the function body.

Example:
float avg(int m1, int m2, int m3)
{
     int tot=m1+m2+m3;
     return(tot/3.0);
}

Note: While defining a function, there is no semicolon(;) after the parenthesis in the function header, unlike while declaring the function or calling the function.

Function Header:

The function header of the function definition contains the type specification of the value returned by the function, followed by the function name, and optionally a set of arguments, separated by commas and enclosed in parentheses. The type specifications can be omitted if the function returns an integer or a character. An empty pair of parentheses must follow the function name if the function definition does not include any arguments. If the function definition contains parameters, separated by commas and enclosed in parentheses.

Argument Declaration:

Arguments are of two types actual arguments and formal arguments. Formal argument declarations follow the first line. All formal arguments must be declared at this point in the function. Each formal argument must have the same data type as its corresponding actual arguments. The formal arguments allow information to be transferred from the calling portion of the program to the function. They are also known as parameters or formal parameters. The corresponding arguments in the calling function are called actual arguments.

Function body:

The remaining part of the function definition is a compound statement that defines the action to be taken by the function. This compound statement is sometimes referred to as the body of the function. It must be followed by the formal argument’s declaration. The body of the function can also call other functions.

The function body contains the declarations and the statements(algorithm) necessary for performing the required task. The body is enclosed within curly braces { … } and consists of three parts.

  1. local variable declaration (if required).
  2. function statements to perform the task inside the function.
  3. a return statement to return the result evaluated by the function (if the return type is void, then no return statement is required).
Return Statement:

A function may or may not send back any value to the calling function. If the function does, it is done through the return statement. Information is returned from the function to the calling portion of the program via the return statement. The return statement also causes control to be returned to the point from which the function was accessed.

Syntax: return(expression); Here the expression may be variable, constant, or expression.

Example: return (a) or return (a+b) or return (55);

Here the expression in the return statement is optional. If the expression is omitted, the return statement simply causes control to revert back to the calling portion of the program, without any information transfer. A function definition can include multiple return statements, each containing a different expression. Functions that include multiple branches often required multiple returns.

Accessing a Function:

A function can be accessed (i.e. called) by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments, an empty pair of parentheses must follow the function’s name. The function call may appear by itself (that is, it may comprise a simple expression), or it may be one of the operands within a more complex expression.

The arguments appearing in the function call are referred to as actual arguments, in contrast to the formal arguments that appear in the first line of the function definition (They are also known simply as arguments or actual parameters). In a normal function call, there will be one actual argument for each formal argument. The actual argument may be expressed as constants, single variables, or more complex expressions. However, each actual argument must be of the same data type as corresponding to the formal arguments.

There may be several different calls to the same function from various places within a program. The actual arguments may differ from one function call to another. Within each function call, however, the actual argument must correspond to the formal arguments in the function definition; i.e. the number of actual arguments must be the same as the number of formal arguments and each actual argument must be of the same data type as its corresponding formal argument.

Example to understand User-Defined Functions in C Language:
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
    int n1,n2,sum;
    printf("Enters two numbers: ");
    scanf("%d %d",&n1,&n2);
    sum = addNumbers(n1, n2); // function call
    printf("sum = %d",sum);
    return 0;
}
int addNumbers(int a, int b) // function definition
{
    int result;
    result = a+b;
    return result; // return statement
}
Output:
Program to understand User-Defined Functions in C Language
Calling Conversions:

As a programmer, it is our responsibility to indicate which sequence parameters are required to create. Always calling conversions will decide in which sequence parameters are created i.e. left to right or right to left. In the C programming language calling conversions are classified into 2 types:

  1. cdecl
  2. pascal
cdecl calling conversions:

In this calling conversion, parameters are created from right to left. By default, any function calling conversion is cdecl. When we are working with cdecl calling conversion that recommends placing the function name in lower case.

pascal calling conversions:

In this calling conversion, parameters are created from left to right. In pascal calling conversion, recommended placing the function name in uppercase. Generally, in a database pascal calling conversion is available like an oracle.

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.
Understanding the main() function in C.
  1. The main () function is an identifier in the program which indicates the starting point of program execution. The main () function is a user-defined function with the pre-implemented signature of the linker. Always linker will be searching to start the program from main() only that’s why main() function should be required.
  2. Without using the main() function we can design the program but we can’t execute it because compilation can be a success but the execution is a failure (linker error will occur).
  3. In any application only one main() function should be required, if we are placing more than one main() function then the compiler will give an error i.e. multiple declarations for main().
  4. Generally, the main function does not return any value that’s why the return type of the main function is void. In implementation when we need to return the exit status of an application then the main function return type should be an int.
  5. The void main() function does not provide any existing status back to the OS. int main function will provide existing status back to the operating system i.e. success or failure.
  6. When we need to inform the existing status as success then need to return “0” i.e. return 0; exit success. When we need to inform the exit status as a failure then the return value should be 1 i.e. return 1; exit failure
  7. When the main function return type is mentioned as an integer type then it is possible to return the values from -32768 to 32767 but those are all meaningless exit statuses except 1 and 0. When the user is terminated the program explicitly then the exit code is -1.
Note:

The c program is a combination of pre-defined and user-defined functions. Always compilation process starts from Top to Bottom and the execution process starts on main() and ends with main() only. In order to compile a program, if any function occurs then with that function name one unique identification value is created called the address of the function.

Follow Us On