A program uses a function named convert() in addition to its main function. The
function main() declares the variable x within its body and the function convert
declares two variables y and z within its body, z is made static. A fourth variable m is
declared ahead(ie at top) of both the functions. State the visibility and lifetime of
each of these variables.
Answers
Very often in computer programs there is some code that must be executed multiple times in different places in the program.
It is also common to need the same code in multiple different programs.
Encapsulating frequently-used code into functions makes it easy to re-use the code in different places and/or different programs.
Separating code out into functions also allows the programmer to concentrate on different parts of the overall problem independently of the others.
In "top-down" programming a programmer first works on the overall algorithm of the problem, and just assumes that functions will be available to handle individual details.
Functions can then be concentrated on independently of the greater context in which they will be used.
Well-written functions should be general enough to be used in a wide range of contexts, not specific to a particular problem.
Functions can be stored in libraries for later re-use. Examples of functions we have used include log( ), sqrt( ), abs( ), cos( ), etc.
The general syntax of a function is as follows:
return_type function_name( arg_type argument, ... ) {
local_variable_type local_variables;
executable statement(s);
return return_value;
}
Example:
int add( int a, int b ) {
int sum;
sum = a + b;
return sum;
}