A function is a block of code that performs a specific task and can be invoked, or called, from various parts of a program.
Functions are a fundamental building block in C and play a crucial role in organizing code, improving modularity, and facilitating code reuse.
Here are the key components and concepts associated with functions in C:
Function Declaration:
A function in C must be declared before it is used. The declaration specifies the function's name, return type, and the types of its parameters (if any).
int add(int a, int b);
Function Definition:
The function definition provides the actual implementation of the code. It includes the function's body, which contains the statements that are executed when the function is called.
int add(int a, int b)
{
return a + b;
}
Function Prototype:
A function prototype is a declaration that provides just enough information about the function to allow its use in the program. It typically appears at the beginning of the program or in a header file.
int add(int a, int b);
Function Call:
To execute the code within a function, it must be called from another part of the program. The function call specifies the function name and passes any required arguments.
int result = add(3, 5); // Calling the add function
Return Statement:
The return statement is used to send a value back from the function to the point in the program where the function was called. It also terminates the function's execution.
int add(int a, int b)
{
return a + b;
}
Function Parameters:
Parameters are variables listed in a function's declaration and definition. They act as placeholders for values that will be provided when the function is called.
int add(int a, int b)
{
return a + b;
}
Return Type:
Functions in C can return a value to the calling code. The return type specifies the type of the value that the function will return. If a function does not return a value, its return type is declared as void.
// Function with no return value
void displayMessage()
{
printf("Hello, World!\n");
}
Void Functions:
Functions that do not return a value are called void functions. They are often used for tasks that don't require a result, such as printing output or performing actions without producing a specific value.
void displayMessage()
{
printf("Hello, World!\n");
}
0 Comments
If you have any doubts, Please let me know