Here’s a code example in C demonstrating function declarations and definitions. This program contains a function to calculate the square of a number, which is declared at the beginning of the program and then defined after main
.
#include <stdio.h> // Function declaration (also called function prototype) int square(int num); int main() { int number, result; printf("Enter a number to find its square: "); scanf("%d", &number); // Function call result = square(number); printf("The square of %d is %d\n", number, result); return 0; } // Function definition int square(int num) { return num * num; }
Explanation of Function Declarations and Definitions
1. Function Declaration (Prototype)
The function declaration, or prototype, specifies the function’s name, return type, and parameter types but does not contain the actual implementation.
Syntax: return_type function_name(parameter_type parameter_name);
In this example: int square(int num);
int
is the return type, meaning the function will return an integer.square
is the name of the function.(int num)
specifies the parameter type (int
) and the parameter name (num
).
The declaration tells the compiler about the function’s existence and allows it to check calls to square in the code for correct usage.
2. Function Definition
The function definition contains the actual code that performs the task.
Syntax: return_type function_name(parameter_type parameter_name) { /* function body */ }
In this example:
int square(int num) { return num * num; }
int square(int num)
matches the prototype in both return type and parameters.
The function calculates the square of num
and returns the result.
3. Calling the Function
In main
, we prompt the user to enter a number, read it into number
, and call square(number)
.
The square
function takes number
as an argument, computes its square, and returns the result.
result = square(number);
stores the return value from square
in result
, which is then printed.
Output Example
If the user enters 4
, the program output will be:
Enter a number to find its square: 4 The square of 4 is 16
Summary
- Function Declaration: Specifies the function signature so the compiler knows about it before the actual definition.
- Function Definition: Contains the code for what the function does.
- Function Call: Executes the function, using the argument provided in the call to perform its task and potentially return a result.
Using functions allows you to modularize code, making it more organized, reusable, and easier to read.