Scope

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;
}

Note

If two variables by the same name are in scope at the same time, the one with the narrower scope is used.
Self-test
  1. Define "scope".
  2. What is the scope of a variable defined at the beginning of a function?