Declaring functions
in C is a crucial step in providing information to the compiler about the existence, structure, and usage of functions within a program. Function declarations are typically placed at the beginning of a C file or in header files to allow the compiler to understand the functions before encountering their actual implementation.
Syntax for Declaring Functions:
return_type
function_name
(
parameter_type1
,
parameter_type2
, ...);
Components:
1. return_type
: Specifies the type of value the function will return (e.g., int, float, void).
2. function_name
: The name of the function that uniquely identifies it within the program.
3. (parameter_type1, parameter_type2, ...):
Specifies the types of parameters the function accepts. If a function takes no parameters, the parentheses are left empty.
Example:
int
add
(
int
a
,
int
b
);
Function definitions
Function definitions provide the actual implementation of the function's behavior. The definition includes the function's body, which contains the statements executed when the function is called.
Syntax for Defining Functions:
return_type
function_name
(
parameter_type1
,
parameter_type2
, ...) {
return
return_value;
}
Example:
int
add
(
int
a
,
int
b
) {
return
a
+
b
;
}
In this example:
1. The function add takes two integer parameters (a and b).
2. The body contains the statement return a + b;, which adds the two parameters and returns the result.
Combining Declaration and Definition:
Defining a function is like creating a recipe. First, you list the ingredients and steps (declaration). Then, you provide the detailed instructions on how to use those ingredients (definition). It's common to keep both the list and the instructions in the same file for clarity and efficiency
Copy Code
int
add
(
int
a
,
int
b
);
int
add
(
int
a
,
int
b
) {
int
sum
=
a
+
b
;
return
sum
;
}