Introduction to Functions in C

Do you know what’s the easiest way to make your code readable, manageable, and reusable? It’s simple! Use functions. Through functions you can divide your code into manageable chunks which you can reuse whenever you want. In this tutorial, we will learn what a function is, what benefits it offers, how to write and call your own functions, types of functions and some of the best practices to adopt while defining your functions. So, let’s dive in. 


What is a Function?

A function is a block of code meant to perform a specific task. For example, the following function is written to perform the task of adding two numbers:

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

The job of the above function is to add two numbers and return the result of addition to someone interested.

You might be wondering why to write functions? There are several benefits a function offers. Let’s see what those are.


Benefits of writing Functions

The benefits of writing functions are:

  1. Modularity:  refers to breaking down complex code into manageable chunks. These chunks are often called modules. These modules are easier to work with and functions can help us achieve this goal. 
  2. Reusability:  modularity leads to reusability. Functions can be defined once and reused whenever the need arises. 
  3. Eliminates redundancy:  reusability eliminates redundancy. There is no need to write the same piece of code again and again. Define once and use multiple times. 
  4. Maintainability:  refers to the simplification in updating and debugging code. A function can be defined at one location, and the changes will reflect wherever it is called. Also, finding errors in the code becomes easier as the nature of the error tells the part of the code which can cause error. Hence, debugging (finding errors) is easy.
  5. Abstraction:  Functions hide implementation details from the user, and hence let the user not worry about how the function works. They can directly use them according to their needs. For example, while using the printf() function, we never worried about how it is displaying the result on the screen. 

These are some of the benefits of writing our own functions. Now, we are fully ready to learn how to define our own functions.


Defining a Function

Let’s learn how to write (or define) our own functions. The syntax of a typical function is as follows:

return_type function_name(parameter_list) {
    // Function body
}

According to the syntax, to define a function, you need to specify:

  • The return type:  what type of value a function will return as the result (int, float, double, char, void). Only, the void data type tells the function will return nothing. 
  • The function name.
  • The parameter list:  inputs to the function.
  • Function body:  describes the main logic of the task to perform.

Comparing with the example of adding two numbers:

int add(int a, int b) {
    int sum;
    sum = a + b;
    return sum;
}
  • ‘int’ is the return type of the function. It indicates the type of the result obtained while performing a specific task. In our example, the task is to perform addition of two numbers and therefore, the result is the addition of two numbers, and the type of the result is an integer.
  • ‘add’ is the name of the function.
  • The parameter list consists of two variables a and b of type integer. This can be thought of as inputs to the function.
  • Within curly braces is the body of the function which describes the logic to perform the task in hand. In our example, the task is to add two numbers and for this purpose:
    • Variable sum is defined to store the sum.
    • Values of a and b are added using the plus operator and the result is stored in sum.
  • ‘return sum’ is a special line within curly braces which is used to return the result of addition to the caller of the function. Note that ‘return’ is a keyword.

🧠 Think for a moment: 

What if my function wants to return multiple values?

Answer:  returning a single value is straightforward. Returning multiple values from a function is not a straightforward process. We can’t return multiple like we return a single value, but there is a way out. Returning multiple values from a function is possible, but to understand how to achieve this, we need to wait until we discuss the concept of call by value and call by reference. We will discuss it later. 


Calling a Function

To use a function, it is important to call it. Calling a function means asking a function to perform the intended task. A function can be called anywhere in the code. The following example shows how to call the ‘add’ function within the main() function:

#include <stdio.h>

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

int main() {
    int result;
    result = add(10, 20);
    printf("Result: %d", result);
    return 0;
}

Output:

30

Explanation:

Focus on line #2 of the main() function: 

result = add(10, 20);

The function add() is called with two values 10 and 20. These are the actual values passed to the function which will be received by variables a and b in the same order. So, variable a receives value 10 and b receives 20. The add function will calculate the sum of 10 and 20, and return the result to the caller which is the main() function. The result of addition is provided to the result variable. The following illustration demonstrates the flow of execution of the function call:

Calling a Function Illustration
The Process of Calling a Function

Declaring Functions

In programming languages like C and C++, it is important to declare your functions before defining and calling them in your code. Declaration of a function informs the compiler about the function name, the types of inputs it receives and the type of result it returns. 

Note:  If you don’t declare your functions, then you can still define them, but you will be restricted to write your functions before the code where they are called. For example, if a function is called within main(), the definition of the function should appear before it. Declaration gives you freedom to write your functions even after the code where it is called. So, it is advisable to declare your functions before you define them in your code.

The declaration for our add function looks like this:

int add(int, int);

The main purpose of declaring functions is to inform the compiler about the return type, name, and the data types of the parameters passed to the function. We can also specify the names of the parameters if we want like the following:

int add(int a, int b);  // valid prototype. 

Note: the concept of function prototype was first introduced in C99 standard.

The complete program of adding two numbers with the function prototype is as follows:

#include <stdio.h>

int add(int, int);   // add function prototype

int main() {
    int result;
    result = add(10, 20);
    printf("Result: %d", result);
    return 0;
}

// Look how I can write my add function after the main() function where it is called :) 
int add(int a, int b) {
    int sum;
    sum = a + b;
    return sum;
}

As mentioned, the function prototype can be written with or without variables. The following program is also valid:

#include <stdio.h>

int add(int a, int b);   // Function prototype with variable names.

int main() {
    int result;
    result = add(10, 20);
    printf("Result: %d", result);
    return 0;
}

// Look how I can write my add function after the main() function where it is called :) 
int add(int a, int b) {
    int sum;
    sum = a + b;
    return sum;
}

Try it yourself

Type the following code in your Code::Blocks editor (or whatever you like)  and remove the function prototype from the code. What did you observe?

#include <stdio.h>

int add(int a, int b);   // Function prototype with variable names.

int main() {
    int result;
    result = add(10, 20);
    printf("Result: %d", result);
    return 0;
}

// Look how I can write my add function after the main() function where it is called :) 
int add(int a, int b) {
    int sum;
    sum = a + b;
    return sum;
}

Post your observations in the comment section below and share your thoughts 🙏


Types of Functions

There are two types of functions:

  1. Predefined functions
  2. User-defined functions

Predefined functions are the built-in functions defined by someone in the standard library. These functions are readily available and can be used whenever needed. While using these functions, we don’t know how they work. The functionality is hidden. For example, the printf() and scanf() functions are predefined functions and we cannot change the logic of these functions.

User-defined functions, on the other hand, are defined by users (programmers like us). This means we can define our own functions according to our needs and hence have the full liberty to change the logic of these functions whenever we want. 

Try it yourself

What do you think – main() function is predefined or user-defined?

Answer:  main() function is a user-defined function as the body of this function (the logic) is defined by users (programmers).


Functions – Best Practices

  1. Use descriptive names for functions:  the name of your function should clearly describe its purpose. For example, if the function is defined to add two numbers, then maybe a good name could be “add_numbers”. 
  2. Keep functions small and focused:  ideally, a function should solve a single problem in hand. So, try defining your functions dedicated to serving a single task. If at all, at some point you realize your function is becoming complex and big, try breaking it down into smaller functions. 
  3. Avoid using global variables:  minimize the use of global variables whenever possible. Global variables are accessible to the entire program and hence, any function can update it. This may lead to errors that may be too difficult to catch. If two or more functions are using the same set of variables, consider passing them through function calls as arguments.
  4. Document your functions:  use comments to document your functions for readability and future reference.

Check Your Understanding

Question 1

What’s wrong with the following function?

int fun(int a, int b) {
    ret a * b;
}
fun is not a valid name for a function
int is not a valid return type
ret is not a keyword
None of the above
explanation

The keyword return should be used in place of ‘ret’.

Question 2

Which of the following function names is descriptive?

x
hello5
print_triangle
_99
explanation

Out of all the names mentioned, only print_triangle is describing the purpose of the function. Maybe the function is defined to print a triangle on the screen.

Question 3

Determine the output of the following program:

#include <stdio.h>

char fun(char);

int main() {
    printf("%c", fun('c'));
    return 0;
}

char fun(char c) {
    return c + 5;
}
104
h
Compilation error
None of the above
explanation

the function fun is receiving the character ‘c’ from the caller (fun() is called in the main() function) and is adding 5 to it. The ASCII value of character ‘c’ is 99 and adding 5 to it gives 104. The function is returning this value as a character because the return type is char. The character ‘h’ has the ASCII value of 104 and as the printf() function is using the %c format specifier, the character ‘h’ will be displayed.

Your score is out of


Conclusion

Functions are useful constructs in C programming as they allow the creation of chunks of code meant to perform specific tasks. In this way, the code can be divided into multiple pieces which are easy to manage and debug.



Leave a comment

Leave a comment

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

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.