Skip to content

Functions in C

A function is a self-contained block of statements that perform a coherent task of some kind.Basically, every C program is a collection of functions. A function can be thought of as a person assigned to do a specific task. Sometimes assigning and working with functions is very easy, while sometimes it can be a bit complex.

Note: Every C program has at least one function, that is the main() function.

Declaring a Function

A function declaration consists of mainly 3 parts:-

(i) Name of the function

(ii) Return Type

(iii) Parameters

Syntax:

return_type function_name(parameter list){

Body of the function

}

Defining a Function

A function consists of mainly two parts, a header and a body. Let’s look at all the parts that make up a function below:-

(i) Return Type:- The return type of the function is basically the data type of the value which the function returns on execution. In some cases where the function does not return any value, the return type is void.

(ii) Function Name:- This specifies the actual name of a function.

(iii) Parameters:- A parameter is like a placeholder, which refers to the type, order, and number of the parameters of a function. But, it is not necessary for a function to contain parameters.

(iv) Function Body:- It is a collection of statements that defines what the function actually does.

Example:-

Output:-

Calling a Function

Calling a function is an important part of any C program. A function is always called inside a program where it is required to be called. When a program calls a function, it transfers all the program control to the called function. A called function performs a specifically-defined task and when it is executed, it returns the program control back to the main program. A function is merely called by its name in the main() function of a C program. To call a function, we just need to pass the required parameters along with the function name.

Example:-

Output:-

Methods of calling a Function

Call by Value

It is a method to pass the values of the arguments which are stored or copied into the formal parameters of the function. The changes made in the parameters inside the function have no effect on the arguments, that is, the original values remain unchanged.

Call by Reference

In this method, the address of a variable is passed as the argument to a function. Since the function now has access to the address of the variable, it can change its value and hence, can easily update the original values.

Note:- By default, C programming uses the call by value method.

Function Arguments

To use arguments in a function, variables must be declared that accept the values of the arguments. These variables are known as formal parameters of the function. These formal parameters act like other local variables inside the function. They get created upon entry into the function and are automatically destroyed upon exit from the function.

Need for Functions in C

(i) Functions help in minimizing redundancy in the C program. If the same process is being carried out at multiple places in a program, then instead of writing the same code again and again, we create a function and call it at all those places. This also makes it easier to change the code at multiple places in the future.

(ii) Functions make a long and unreadable code systematic and easier to read. A code looks much more beautiful and modular if functions are used.

(iii) Functions provide abstraction.

Types of Functions in C

There are two types of functions in C :-

(i) Library Functions:- These are the functions which are declared in the C header files, such as printf(), scanf(), gets(), etc.

(ii) User-Defined Functions:- These are the functions which are created by the user with the motive to be used multiple times. They reduce complexity of big C programs and make them optimal.

The Main Function

The main function is a special function and is a must for every C program. The compiler starts running and executing the code from the beginning of the main function.

Types of Main Function

There are two types of main function:-

(i) Main function without parameters

(ii) Main function with parameters

The main function is given an option to have or not have parameters to allow input from the command line.

Advantages of Functions in C

(i) It helps reduce redundancy in C programming.

(ii) We can call functions multiple times in the entire program.

(iii) It optimizes the program and makes it easily readable.

Library Functions in C

Library functions are in-built functions in C programming that are grouped and placed at a common place known as the library. These functions are used to perform specific operations. For example, printf is a library function used to print on the console. As discussed earlier, all library functions are defined inside the different header files saved with the extension .h. These header files need to be included in the program to use these library functions.

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

Return Values and their Types

A function may or may not send back any value to the calling function post-execution. If it does, it is done through the return statement. While it is possible to pass to the called function any number of values, the called function can only return one value per call, at the most.

The return statement can take one of the following forms:-

return;

OR

return expression;

In the first case, the plain ‘return’ does not return any value. It acts similar to the closing brace of the function. When a return is encountered, the control is immediately passed back to the calling function.

In the second case, it returns the value of the expression.

Categories of Functions

A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories:-

(i) Functions with no arguments and no return values

(ii) Functions with arguments and no return values

(iii) Functions with arguments and one return value

(iv) Functions with no arguments but return a value

(v) Functions that return multiple values

No Arguments and No Return Values

When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. Hence, there is no data transfer between the calling function and the called function.

This category of functions cannot be used in an expression. It can only be used as an independent statement.

Arguments but No Return Values

This is an apparently wiser approach because the calling function can check for the validity of data, if necessary, before it is handed over to the called function. In this case, the actual and formal arguments should match in number, type, and order. If the actual arguments are more than the formal arguments, then the extra actual arguments are discarded. Whereas, if the actual arguments are less than the formal arguments, then the unmatched formal arguments are initialized to some garbage values. Any mismatch in data types may also result in passing of garbage values.

Arguments with Return Values

We may not always wish to have the result of a function displayed. We may use it in the calling function for further processing. For example, different programs may require different output formats for display of results. These shortcomings can be overcome by handing over the result of a function to its calling function where the returned value can be used as required by the program.

No Arguments but Returns a Value

There could be occasions where we may need to design functions that may not take any arguments but return a value to the calling function. A typical example is the getchar function declared in the header file <stdio.h>. This function in C programming has no parameters but it returns an integer type data that represents a character.

Nesting of Functions

C programming permits nesting of functions freely. main can call function1, which calls function2, which calls function3, and so on. There is, in principle, no limit as to how deeply functions can be nested.

Syntax:-

int main(){//main function in C

return_type function_name();//Call function under the main function

return 0;

}

return_type function_name(){//user defined function //statements of function

}

For example:-

#include <stdio.h>

#include <stdlib.h>

int main()

{

printf(“This is main method in c\n”);

function_one();

getch();

return 0;

}

void function_one()

{

printf(“This is a user defined function\n”);

function_two();

}

void function_two()

{

printf(“This is nested function in c\n”);

}

Recursion

When a called function in turn calls another function, a process of ‘chaining’ occurs. Recursion is a special case of this process, where a function calls itself.

For example:-

main()

{

printf(“This is an example of recursion.\n”);

main();

}

This block of code will produce an output as follows:

This is an example of recursion.

This is an example of recursion.

This is an example of recursion.

This is an example of recursion.

This is an example…

Execution is terminated abruptly, otherwise it continues indefinitely.

Passing Arrays to Functions

Like the values of simple variables, it is also possible to pass the values of an array to a function.

Rules to Pass an Array to a Function

(i) The function must be called by passing only the name of the array.

(ii) In the function definition, the formal parameter must be an array type, the size of the array does not need to be specified.

(iii) The function prototype must show that the argument is an array.

Passing Strings to Functions

In C programming, strings are treated as character arrays and therefore, the rules for passing strings to functions are very similar to those for passing arrays to functions.

Rules for Passing Strings to Functions

(i) The string to be passed must be declared as a formal argument of the function when it is defined.

(ii) The function prototype must show that the argument is a string.

(iii) A call to the function must have a string array name without subscripts as its actual argument.

nv-author-image

Vaibhav Kapoor

A professional web entrepreneur, WordPress developer and digital marketing strategist with more than 4 years of experience in building a business from scratch. Knowledgeable about SEO, blogging, internet marketing, social media and website development.

Leave a Reply

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

[wpfepp_submission_form form="1"]