Functions
often require input data, known as parameters, and they can provide output data, known as the return type. Let's explore the details of function parameters and return types:
Function Parameters:
1. Syntax for Declaring Parameters:
Parameters are variables that a function can accept. They are declared within parentheses in the function declaration and definition.
return_type
function_name
(
parameter_type1
parameter_name1
,
parameter_type2
parameter_name2
, ...) {
}
2. Passing Values to Functions:
When you call a function, you provide values for its parameters. These values are called arguments.
.
int
add
(
int
a
,
int
b
) {
return
a
+
b
;
}
int
result
=
add
(
3
,
5
);
3. Types of Parameters:
Parameters can be of different types, such as integers, floats, characters, or custom-defined types.
void
printMessage
(
char
message
[]) {
printf
("
%s
\n",
message
);
}
Return Types:
1. Syntax for Return Types:
The return type specifies the type of value that the function will return. It is declared before the function name.
return_type
function_name
(
parameter_type1
parameter_name1
,
parameter_type2
parameter_name2
, ...) {
}
2. Returning Values:
The return statement is used to send a value back to the calling part of the program. The type of the return value must match the declared return type.
int
square
(
int
x
) {
return
x
*
x
;
}
int
result
=
square
(
4
);
3. Void Return Type:
Functions with no return value use the void keyword.
void
greet
() {
printf
("Hello!\n");
}
Notes:
a. Matching Types:
1. The types of function parameters in the declaration and definition must match.
2. The type of the value returned by the function must match the declared return type.
b. Multiple Parameters:
1. Functions can have multiple parameters, allowing them to accept and process more data.
int
addThreeNumbers
(
int
a
,
int
b
,
int
c
) {
return
a
+
b
+
c
;
}