Functions in C
Functions in C
In C, functions are blocks of code designed to perform specific tasks. They allow for modular
programming,
1. Anatomy of a Function:
return_type function_name(parameter_list) {
// Function body
Components:
- Return Type: Specifies the type of value the function returns (e.g., int, float, char, void).
Example:
Functions must be declared before they are used. A function declaration tells the compiler about the
function's name, return type, and parameters.
Syntax:
return_type function_name(parameter_list);
Example:
3. Function Definition:
This is where the actual implementation of the function is provided. It matches the declaration.
Example:
4. Function Call:
To execute a function, use its name followed by parentheses containing arguments (if any).
Example:
5. Types of Functions:
- Returning a Value:
Example:
- Void Functions:
Example:
void printMessage() { printf("Hello, World!"); }
b. Based on Arguments:
- Global Functions: Declared outside any function. Accessible throughout the program.
- Static Functions: Declared with static. Accessible only within the file.
Example:
7. Recursion:
Example:
int factorial(int n) {
if (n == 0) return 1;
}
8. Advantages of Functions:
- Scalability: Functions can be added or modified without affecting the rest of the program.
9. Example Program:
#include <stdio.h>
// Function declaration
void printMessage();
int main() {
// Function call
printMessage();
return 0;
// Function definition
void printMessage() {
Key Notes:
- Parameters are passed by value by default in C. To modify original data, use pointers.
- Use meaningful names for functions and parameters for better readability.