Skip to main content

Functions in C: An Introduction

Introduction to Functions in C

Functions in C programming are subroutines, also known as routines, subprograms or methods, that perform a specific task. They are the building blocks of a C program and contribute to code reusability. In this tutorial, we will learn about the basics of functions in C.

What is a Function in C?

A function in C is a group of statements that together perform a task. Each C program has at least one function, which is main(), and all the most trivial programs can define additional functions. We can divide a large C program into small blocks which can perform a certain task. A function is a block of code that performs a specific task.

Function Declaration, Definition, and Call

A C function consists of a function declaration, function call, and function definition.

  1. Function Declaration: The function declaration tells the compiler about a function's name, return type, and parameters. A function declaration is optional if the user defines a function before calling it.
int sum(int a, int b);
  1. Function Call: The function call is the place of a program where we use the function. We pass the required parameters, and if the function returns a value, then we store it.
int total = sum(10, 20);
  1. Function Definition: The function definition provides the actual body of the function.
int sum(int a, int b) {
return a+b;
}

Types of Functions in C

There are two types of functions in C:

  1. Standard library functions: These are functions that are part of the standard library in C. They are declared in the header files and include functions like printf(), scanf(), sqrt(), and more.

  2. User-defined functions: These are functions that are defined by the user for specific tasks. The user can define them, call them whenever required, and use them as many times as required.

The main() Function

Every C program has one main() function. Program execution begins from the main() function. No function can be called main(). This function must be present for the program to run.

int main() {
// code
return 0;
}

Function Arguments and Return Values

Functions in C can be called with arguments and may return a value.

  1. Function Arguments: If a function needs to perform operations on some values, these values can be passed as function arguments.
void printSum(int a, int b) {
printf("Sum = %d", a+b);
}
  1. Return Values: Functions can also return values. The return_type is the data type of the value the function returns. If the function does not need to return a value, we can use void.
int getSum(int a, int b) {
return a+b;
}

Conclusion

This tutorial covered the basics of functions in C, including what they are, how to declare, define, and call them, the different types, and how to use arguments and return values. Functions are a crucial part of C programming, and understanding them is key to building efficient and reusable code.