Defining Functions
Functions in C allow you to encapsulate a block of code, making the code modular and promoting reusability. Let's explore how to define and use functions in C.
Function Definition
A function in C is defined using the following syntax:
return_type function_name(parameters) {
// Function body
// Code to be executed
return value; // Optional return statement
}
return_type
: The type of the value the function returns. It can bevoid
if the function doesn't return a value.function_name
: The name of the function.parameters
: The input parameters that the function takes (if any).return value
: The value the function returns (if applicable).
Here's an example of a simple function:
#include <stdio.h>
// Function definition
void greet() {
printf("Hello, world!\n");
}
int main() {
// Function call
greet();
return 0;
}
In this example, the greet
function is defined with a void
return type, meaning it doesn't return any value. It prints "Hello, world!" when called from the main
function.
Last modified: 25 February 2024