FUNCTION
Introduction
Functions are used to provide modularity to the software. By using functions, you can divide complex tasks into small manageable tasks. The use of functions can also help avoid duplication of work. For example, if you have written the function for calculating the square root, you can use that function in multiple programs.
Program
#includeint add (int x, int y) //A { int z; //B z = x + y; return (z); //C } main () { int i, j, k; i = 10; j = 20; k = add(i, j); //D printf ("The value of k is%d\n", k); //E }
Explanation
-
When defining the name of the function, its return data type and parameters must also be defined. For example, when you write
int add (int x, int y)
int is the type of data to be returned, add is the name of the function, and x and y are the parameters of the type int. These are called formal parameters.
-
The body of a function is just like the body of main. That means you can have variable declarations and executable statements.
-
A function should contain statements that return values compatible with the function's return type.
-
The variables within the function are called local variables.
-
After executing the return statement, no further statements in the function body are executed.
-
The name of the function can come from the arguments that are compatible with the formal parameters, as indicated in statement D.
-
The arguments that are used in the call of the function are called actual parameters.
-
During the call, the value of the actual parameter is copied into the formal parameter and the function body is executed.
-
After the return statement, control returns to the next statement which is after the call of the function.
Points to Remember
-
A function provides modularity and readability to the software.
-
To define the function, you have to define the function name, the return data type and the formal parameters.
-
Functions do not require formal parameters.
-
If the function does not return any value, then you have to set the return data type as void.
-
A call to a function should be compatible with the function definition.
No comments:
Post a Comment