In C, a function is a block of code that performs a specific task, and can be called and executed by its name from other parts of the program. Functions allow the programmer to modularize and reuse code, making it easier to maintain and debug.
Types of Functions in C
1. Standard Library Functions: These are built-in functions provided by the C standard library, like printf(), scanf(), strlen(), etc.
2. User-Defined Functions: Functions that you define yourself to perform specific tasks.
How to define and call a Function in C
To define a function, you need to specify
1. Return type: The type of value the function will return (e.g., int, float, char, or void if no return value is required).
2. Function name: The name by which the function can be referenced.
3. Parameters (optional): A list of variables that the function will accept as input (optional).
4. Function body: The block of code that defines what the function does.
Syntax:
return_type function_name(parameters) {
// function body
// code to perform specific task
return value; // Optional if return_type is not void
}
Explanations:
- return_type: Specifies what type of value the function returns.
- function_name: The name of the function.
- parameters: Variables that the function uses to perform its task (can be empty if the function doesn’t require parameters).
- return value: The value returned from the function (if applicable).
Example:
#include <stdio.h>
// Function Definition
int multiply(int a, int b) {
return a * b; // multiply a and b, and returning the result
}
int main() {
int num1 = 10, num2 = 20;
int result;
// Calling the multiply function
result = multiply(num1, num2);
// Displaying the result
printf("The multiply of %d and %d is: %d\n", num1, num2, result);
return 0;
}
Output:
Explanation:
1. Function Definition (multiply): It has two integer parameters a and b, multiply them, and returns their multiply.
// Function Definition
int multiply(int a, int b) {
return a * b; // multiply a and b, and returning the result
}
2. Calling the Function: Inside the main function, we call multiply by passing num1 and num2 as arguments. The returned value is stored in the variable result.
// Calling the multiply function
result = multiply(num1, num2);
3. Displaying the Result: The result of the addition is printed using printf.