Course Content
C Tutorial
About Lesson

Defining and Calling Functions

In the realm of C programming, functions play a pivotal role, serving as the building blocks of code organization and reusability. They encapsulate a set of instructions, execute specific tasks, and can be called multiple times within a program. Let’s delve deeper into comprehending and invoking functions in C.

What Are Functions?

Functions in C are self-contained blocks of code designed to perform a particular task. They consist of a function name, return type, parameters (if any), and a function body. When called, they execute a sequence of statements defined within the body and may return a value.

Function Declaration and Definition

In C, functions are typically declared before they are used. This declaration includes the function’s return type, name, and parameters (if any). The function definition, on the other hand, contains the actual implementation or code that specifies what the function does.

Calling Functions

To execute a function in C, you use its name followed by parentheses containing any required arguments. The function call transfers control from the main program to the called function. Once the function completes its task, it returns control to the point where it was called.

Function Parameters

Functions can take parameters, which act as variables within the function. These parameters allow data to be passed into the function when it’s called. Parameters are specified in the function declaration and definition.

Return Statement

The return statement in C functions is used to send a value back from the function to the calling program. The type of value returned should match the function’s declared return type.

Example:

#include <stdio.h>

// Function declaration
int add(int a, int b);

int main() {
int result;
int num1 = 10, num2 = 20;

// Function call
result = add(num1, num2);

printf("Sum: %dn", result);

return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}

In this example, the add function takes two integers as parameters and returns their sum. The main function calls the add function, passing num1 and num2 as arguments, and displays the result