Functions in C

A function in C is a block of code that performs specific tasks when called. They are also called subroutines or procedures. They are used to perform certain actions and are important in code reuseability: Define the code once and use it multiple times. You can divide your code into separate functions. How you do that is up to you, the objective is that each function performs a particular task.

Defining a function

This contains the actual statements that will be executed when the function is called. It uses the following syntax:

return_type function_name(param1_data_type param1, param2_data_type param2)
{
    // body of the function
}

return_type - This is a data type that function returns

function_name - This is the actual name of the function

paramet_list - The list, order, and number of arguments to be passed to a function.

body of the function - This contains statements to be executed when the function is called.

NOTE:
You have to provide data types for your parameters. If empty you can use the void keyword. This also applies to the return type.

Declaring a function

A function is declared using the return_type, function_name and parameter_list. This informs the compiler of the presence of a function. The parameter_list is optional as you can also use a data type. It uses the following syntax:

return_type function_name(parameter_list);

Example:

int sum(int a, int b);
int sum(int, int);

Calling a function

Once a function is declared it has be be called for it to perform the specified statements. You can do that by writing the return_type, function_name, and parameter_list followed by a semi-colon to indicate the end of a statement.

return_type function_name(parameter_list);

Example:

#include <stdio.h>

/**
* sum - Calculates sum of two numbers
* @a: The first operand
* @b: The second operand
* 
* Return: Sum of two numbers
*/
int sum(int a, int b)
{
    return (a + b);
}

/**
* main - Entry point
* 
* Return: Always 0 (Success)
*/
int main(void)
{
    int add = sum(10, 5);
    printf("Sum is: %d", add);
    return (0);
}

Output

Sum is: 15

Conclusion

In conclusion, functions are essential in C programming as they enable us to break big problems into small and manageable pieces of code. You can declare and define functions in C. It is a good practice to declare your functions before using them and define them at the top of your file or in a separate file. This leads to a cleaner and more readable code which promotes modularity. This way you are able to debug and maintain your code effectively.