Functions in C

In C programming language, a function is a block of code that performs a specific task. Functions provide modularity and reusability to a program by allowing the programmer to break down a complex program into smaller, more manageable pieces.

A function in C has the following parts:

1. Function Declaration: A function declaration tells the compiler about the name of the function, the arguments it takes, and the type of the value it returns (if any). The syntax of a function declaration is as follows:

return_type function_name(argument1_type argument1_name, argument2_type argument2_name, ...);

Here’s an example of how to declare a function in C:

int add(int a, int b);

In this example, we declare a function named “add” that takes two integer arguments “a” and “b” and returns an integer value.

2. Function Definition: A function definition provides the implementation of the function. It specifies what the function does when it is called. The syntax of a function definition is as follows:

return_type function_name(argument1_type argument1_name, argument2_type argument2_name, ...) {
    // code to execute
    return value;
}

Here’s an example of how to define a function in C:

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

In this example, we define the “add” function that takes two integer arguments “a” and “b” and returns the sum of the two integers.

3. Function Call: A function call is used to execute the code inside the function. The syntax of a function call is as follows:

function_name(argument1, argument2, ...);

Here’s an example of how to call a function in C:

int a = 5, b = 10, c;

c = add(a, b);

In this example, we call the “add” function with arguments “a” and “b” and store the returned value in the variable “c”.

Functions can also have no arguments or no return value. Here’s an example of a function with no arguments and no return value:

void print_hello() {
    printf("Hello\n");
}

In this example, we define a function named “print_hello” that takes no arguments and does not return a value. It simply prints “Hello” to the console when called.

Functions can also have default values for their arguments and can be recursive, meaning that they call themselves. The return statement can also be omitted if the function does not return a value.

Functions in C are powerful constructs that enable the programmer to write modular and reusable code. They are essential for writing complex programs that are easy to maintain and understand.