The scope of variables
The scope of a variable describes the range of lines in which the
variable may be used.
Some textbooks may also term this the visibility or
lexical range of a variable.
C has only 2 primary types of scope:
- global scope (sometimes termed file scope)
in which variables are declared
outside of all functions and statement blocks, and
- block scope in which variables are declared within a function
or statement block.
01 #include <stdio.h>
02 #include <stdlib.h>
03 #include <string.h>
04 #include <ctype.h>
05
06 static int count = 0;
07
08 int main(int argc, char *argv[])
09 {
10 int nfound = 0;
11
12 // check the number of arguments
13 if(argc != 2) {
14 int nerrors = 1;
15
16 ....
17 exit(EXIT_FAILURE);
18 }
19 else {
20 int ntimes = 100;
21
22 ....
23 exit(EXIT_SUCCESS);
24 }
25 return 0;
26 }
|
|
- The variable count has global scope.
It is defined on line 06,
and may be used anywhere from line 06 until the end of the file (line 26).
The variable count is also preceded by the
keyword static,
which prevents it from being 'seen' (read or written) from outside
of this file rotate.c
- The variable nfound has block scope.
It is defined on line 10,
and may be used anywhere from line 10 until the end of the block in which
it was defined (until line 26).
- The variable nerrors has block scope.
It is defined on line 14,
and may be used anywhere from line 14 until line 18.
- The variable ntimes has block scope.
It is defined on line 20,
and may be used anywhere from line 20 until line 24.
- We could define a different
variable named nerrors in the block of lines 20-24 -
without problems.
- We could define a different
variable named nfound in the block of lines 20-24 -
but this would be a very bad practice!
|
CITS2002 Systems Programming, Lecture 2, p7, 24th July 2024.
|