Functions in C

Functions in C Programming Language

In this article, I am going to discuss the Functions in C Programming Language in detail. Please read our previous articles, where we discussed the Control Statements in C. As part of this article, we are going to discuss the following pointers with examples.

  1. What are the Functions in C?
  2. Types of Functions in C Program
  3. Advantage of functions in C or Why we need functions in C?
  4. Standard Library Functions in C
  5. Advantages of Using Standard Library functions
  6. What are the limitations of pre-defined functions in C?
  7. User-Defined Functions in C
  8. How does the user-defined function work in C?
  9. Advantages of user-defined function
  10. Understanding the main() function in C
What are the Functions in C?

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 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 Program:

There are two types of function in C programming:

  1. Standard library functions
  2. User-defined functions

Functions in C

Syntax:

types of function in C programming

Different Part of a Function:
  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 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 variable according to the return type.

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

Example to understand Functions in C:
#include <stdio.h>

void name();	    /*function declaration */
void message();		/*function declaration */
void main()
{
  name();
  message();
}

void name()		   /*function definition */
{
  printf ("Ram ");
}

void message ()	   /*function definition */
{
  name ();
  printf ("Hello ");
}

Output: Ram Ram 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>.

Advantage of functions in C or Why we need functions in C?
  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, 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:

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

When we are working with pre-defined functions for avoiding the compilation error, we required to go for forwarding declaration i.e. prototype is required. When we 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 prototype, i.e. forward declaration of functions. When we install C Software, some pre-defined functions are 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:

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:
  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?

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 requirement then go for user-defined function.

User-Defined Functions in C:

User-defined functions are the functions which 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?

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

How user-defined function works in C?

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 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 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 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 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:
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, 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:

When a function is declared to perform some sort of calculation or any operation and is expected to provide with 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 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 like other variables in C language.

Parameter list:

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 it 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 function header and the statement(s) within curly braces is called 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 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 correspond 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.

Program to understand user-defined function in C:
#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 function in C

Calling Conversions:

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

  1. cdecl
  2. pascal
cdecl calling conversions:

In this calling conversion, parameters are created towards 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 towards from left to right. In pascal calling conversion, recommended placing the function name in uppercase. Generally, in 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 starts 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 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 than 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 status except 1 and 0. When the user is terminated the program explicitly then exit code is -1.
Note:

A C program is a combination of pre-defined and user-defined functions. Always compilation process starts from Top to Bottom and 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.

In the next article, I am going to discuss Types of User-Defined Functions in C with examples. Here, in this article, I try to explain Functions in C Programming Language. I hope you enjoy this  Functions in C Language article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *