Functions in C
Functions in C are blocks of code that perform a specific task. They allow modular programming, reusability, and easier debugging. A function can have parameters (inputs) and can return a value.
1. Calling Function with Parameters
Functions can accept parameters to perform operations on provided values.
- Example: int add(int a, int b) { return a + b; } int sum = add(5, 3); // sum = 8
2. Calling Function with No Arguments and No Return Value
Functions can be used without parameters and without returning a value. They simply perform a task.
- Example: void greet() { printf("Hello, World!\n"); } greet();
3. Calling Function with Arguments and Return Value
Functions can accept parameters and return a value after performing operations.
- Example: int multiply(int x, int y) { return x * y; } int result = multiply(4, 5); // result = 20
4. Calling Function with No Argument but with Return Value
Functions can return a value without requiring any input arguments.
- Example: int getNumber() { return 10; } int num = getNumber(); // num = 10
5. Local Variables
Local variables are declared inside a function and can only be used within that function. They are created when the function is called and destroyed when the function ends.
6. Global Variables
Global variables are declared outside all functions and can be accessed by any function in the program.
7. Static Variables
Static variables retain their value between function calls and are initialized only once.
8. Call by Value & Call by Reference
Call by value passes a copy of the variable to the function, while call by reference passes the variable's address, allowing the function to modify the original value.
- Example of Call by Value: void addOne(int x) { x = x + 1; } int num = 5; addOne(num); // num remains 5
- Example of Call by Reference: void addOne(int *x) { *x = *x + 1; } int num = 5; addOne(&num); // num becomes 6
Codecrown