C Functions – Introduction, Parameters & Return Types
Functions in C are blocks of code designed to perform a specific task, making programs modular, reusable, and easier to debug.
Introduction to Functions in C
What is a Function?
A function is a self-contained block of code that performs a task. It’s defined once and can be called multiple times.
Syntax:
return_type function_name(parameter_list) {
// code block
}
Example: Basic Function
#include <stdio.h>
void greet() {
printf("Hello, World!\n");
}
int main() {
greet(); // Function call
return 0;
}
Output:
Hello, World!
Function Types
Type | Description |
---|---|
Library Functions | Built-in (e.g., printf , scanf ) |
User-defined | Created by the programmer |
C Function Parameters
Parameters are placeholders for values you want to pass into the function.
Syntax with Parameters:
void displaySum(int a, int b) {
int sum = a + b;
printf("Sum = %d\n", sum);
}
Example: Function with Parameters
#include <stdio.h>
void displaySum(int x, int y) {
printf("Sum = %d\n", x + y);
}
int main() {
displaySum(5, 10);
return 0;
}
Output:
Sum = 15
Types of Parameters
Type | Description |
---|---|
Actual Argument | Passed during the function call |
Formal Parameter | Defined in the function definition |
C Function Return Types
The return type specifies the type of value the function gives back to the caller.
Syntax with Return Type:
int add(int a, int b) {
return a + b;
}
Example: Returning a Value
#include <stdio.h>
int add(int x, int y) {
return x + y;
}
int main() {
int result = add(3, 7);
printf("Result = %d\n", result);
return 0;
}
Output:
Result = 10
Common Return Types
Return Type | Description |
---|---|
void | No value returned |
int | Returns an integer |
float | Returns a floating-point number |
char | Returns a character |
Best Practices
Tip | Reason |
---|---|
Use void when no return needed | Saves memory and improves clarity |
Keep function names descriptive | Easier to understand code |
Keep each function focused | One task per function |
Use comments for parameters | Improves maintainability |
Common Mistakes
Mistake | Problem |
---|---|
Not matching return types | Causes unexpected behavior |
Missing return value | Compiler warnings or logic errors |
Too many parameters in one function | Reduces readability |