In C Language, functions are blocks of code that perform a specific task.
They provide modularity and reusability to the program by breaking it into smaller, manageable pieces.
Here's a basic overview of functions in C:
Before we can use a function in C, we must declare it. This informs the compiler about the function's name, return type, and parameters (if any).
Function declaration usually occurs at the beginning of the file or in header files.
Syntax: return_type function_name(parameters);
The actual implementation of the function is defined separately from its declaration.
It consists of a return type, function name, parameters (if any), and the body of the function enclosed within curly braces "{}".
Syntax: return_type function_name(parameters) { // function body }
Functions can return a value to the caller. The return type specifies the type of value that the function returns. It could be "int", "float", "char", "void", etc.
If the return type is void, the function doesn't return any value.
Parameters are optional. They allow us to pass values to the function for processing.
Parameters are specified within parentheses after the function name in both declaration and definition.
Parameters are separated by commas and consist of a data type followed by a parameter name.
Example: int add(int a, int b) { ... }
To execute a function, we need to call it within your program.
Function calls are written by specifying the function name followed by parentheses () and passing any required arguments inside these parentheses.
Syntax: function_name(arguments);
we have declared the `add` function before main() and called in main() to calculate the sum of two numbers.
#include <stdio.h> // Function declaration int add(int a, int b); int main() { int num1 = 5, num2 = 3; int sum = add(num1, num2); // Function call printf("Sum: %d\n", sum); return 0; } // Function definition int add(int a, int b) { return a + b; }
Sum: 8
#include <stdio.h> // Function declaration int isEven(int n); int main() { int num = 6; if (isEven(num)) // Function call printf("%d is even.\n", num); else printf("%d is odd.\n", num); return 0; } // Function definition int isEven(int n) { return n % 2 == 0; }
we have declared the `isEven` function before main() and called in main() to check is the number is even or odd.
6 is even.
Note: Functions needs to be declare on top of main functions, if wants to use after the main() functions.
#include <stdio.h> // Function declaration float areaRectangle(float length, float width); int main() { float length = 5.0, width = 3.0; float area = areaRectangle(length, width); // Function call printf("Area of rectangle: %.2f\n", area); return 0; } // Function definition float areaRectangle(float length, float width) { return length * width; }
we have declare `areaRectangle` function before main() and calling in main() to calculate Rectangle Area.
Area of rectangle: 15.00