A function in C is a block of code that performs a specific task. Functions allow us to break down a program into smaller, reusable components, improving code readability and maintainability.
The general syntax of a function in C is:
return_type function_name(parameters) { // Function body return value; // optional depending on return type }
- return_type: Specifies the type of value the function returns (e.g., int
, float
, void
).
- function_name: The name of the function.
- parameters: Inputs to the function, which can be variables or constants.
#include// Function declaration void greet() { printf("Hello, World!\n"); } int main() { greet(); // Calling the function return 0; }
greet()
is called in the main()
function. It prints "Hello, World!" when executed.
Functions can also accept parameters to process specific values. Here's an example:
#include// Function declaration void add(int a, int b) { printf("Sum: %d\n", a + b); } int main() { int x = 5, y = 3; add(x, y); // Calling the function with arguments return 0; }
add()
takes two parameters, a
and b
, and prints their sum.
A function can also return a value. Here's an example:
#include// Function declaration int multiply(int a, int b) { return a * b; // Returns the product } int main() { int result = multiply(4, 5); // Calling the function and storing the result printf("Product: %d\n", result); return 0; }
multiply()
multiplies two numbers and returns the result, which is then printed in main()
.
A declaration informs the compiler about the function's signature, while a definition provides the actual body of the function. Here's an example:
#include// Function declaration void hello(); // Function definition void hello() { printf("Hello, World!\n"); } int main() { hello(); // Calling the function return 0; }
hello()
is first declared and then defined, and it's called in the main()
function to print a greeting message.
int
or float
).int
function).Create a program with multiple functions performing different operations, and call them from the main function based on user input. Try to use at least 4 different functions in your program!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!