Variables defined in C and Fortran are in scope (accessible) from where they are defined to the end of the block in which they are defined.
Most variables are defined at the beginning of a subprogram, so they are accessible to all statements in that subprogram and nowhere else.
In C, we can actually define variables at the beginning of any
block of code. In the code segment below, the variable
area is in scope only in the if block.
#include <stdio.h>
#include <math.h> // M_PI
#include <sysexits.h> // EX_*
int main()
{
double radius;
printf("Please enter the radius: ");
scanf("%lf", &radius);
if ( radius >= 0 )
{
double area;
area = M_PI * radius * radius;
printf("Area = %f\n", area);
}
else
{
fputs("Radius cannot be negative.\n", stderr);
return EX_DATAERR;
}
return EX_OK;
}