Functions in C are blocks of code that perform a specific task. They allow you to
break down complex problems into smaller, manageable tasks, improving code
reusability, readability, and maintainability. Functions can accept input in the
form of parameters, and they can return output using return statements.
1. Defining a Function
A function is defined by specifying its return type, name, parameters (if any), and
the block of code to execute.
The syntax of a function definition is:
return_type function_name(parameters) {
// Function body
}
Example:
#include <stdio.h>
// Function declaration
void greet() {
printf("Hello, welcome to C programming!\n");
}
int main() {
greet(); // Function call
return 0;
}
Here, greet() is a function that doesn't take any parameters and doesn't return a
value (its return type is void).
2. Function Types
Functions in C can be broadly classified into two categories:
, 2.1. Void Functions
A function that does not return any value is called a void function. It is defined
with the return type void.
Example:
#include <stdio.h>
void sayGoodbye() {
printf("Goodbye!\n");
}
int main() {
sayGoodbye(); // Calling the function
return 0;
}
2.2. Non-Void Functions
A function that returns a value must specify the return type (such as int, float,
etc.), and it uses the return statement to return the value.
Example:
#include <stdio.h>
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}
int main() {
int result = add(3, 5); // Calling the function
printf("Sum: %d\n", result); // Prints the result
return 0;
}