In C programming language, a function is a block of code that performs a specific task and can be called from other parts of the program. Functions provide modularity and reusability to programs, and make them easier to read, test, and maintain.
A function in C typically consists of the following parts:
- Function header: specifies the function name, return type, and parameter list.
- Function body: contains the statements that define what the function does.
- Function call: invokes the function from within another part of the program.
The syntax for defining a function in C is as follows:
return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...) {
// function body
return return_value; // optional
}
where:
return_type
: specifies the data type of the value that the function returns (such asint
,float
,void
, etc.).function_name
: specifies the name of the function (must be a valid identifier in C).parameter1_type
,parameter2_type
, etc.: specify the data types of the parameters that the function expects to receive (such asint
,float
,char
, etc.).parameter1
,parameter2
, etc.: specify the names of the parameters.return_value
: specifies the value that the function returns (if thereturn_type
is notvoid
).
For example, the following is a definition of a function named sum
that takes two integer parameters and returns their sum:
int sum(int a, int b) {
int result = a + b;
return result;
}
This defines a function named sum
that takes two integer parameters named a
and b
, adds them together, stores the result in a variable named result
, and returns the value of result
. To call this function from within another part of the program, we can use the following syntax:
int x = 5;
int y = 7;
int z = sum(x, y); // z will be assigned the value 12
Comments