Functions
A function in C is a self-contained block of code that performs a specific task and can be called from other parts of a program. Functions are used to organize and structure code, and they allow you to reuse code in multiple places.
Here is an example of a simple function in C:
#include <stdio.h>
int add(int x, int y)
{
return x + y;
}
int main()
{
int result = add(3, 4);
printf("Result: %d\n", result);
return 0;
}
In this example, we have defined a function add that takes two integers as arguments and returns their sum. The function is defined with the int return type, which indicates that it returns an integer value.
The function is called from the main function using the function name and passing the arguments 3 and 4. The return value of the function is assigned to the variable result and is printed to the console using the printf function.
Functions can also be defined to take no arguments or to return no value. For example:
#include <stdio.h>
void print_message()
{
printf("Hello, world!\n");
}
int main()
{
print_message();
return 0;
}
In this example, we have defined a function print_message that takes no arguments and returns no value. The function is defined with the void return type, which indicates that it does not return a value. The function simply prints a message to the console.
Functions can be defined with different parameter lists and return types, and they can be called multiple times from different parts of the program. Functions are a powerful and important feature of the C language, and they are used to organize and structure code in a modular way.