Sams Teach Yourself C in 21 Days

(singke) #1
scope. For this reason, you can leave a structure body external to any functions
with no real effect on memory. Many programmers put commonly used structure
bodies with tags into header files and then include these header files when they
need to create an instance of the structure. (Header files are covered on Day 21.)
Q How does the computer know the difference between a global variable and a
local variable that have the same name?
AThe answer to this question is beyond the scope of this book. The important thing
to know is that when a local variable is declared with the same name as a global
variable, the program temporarily ignores the global variable when the local vari-
able is in scope (inside the function where it is defined). It continues to ignore the
global variable until the local variable goes out of scope.
Q Can I declare a local variable and a global variable that have the same name,
as long as they have different variable types?
AYes. When you declare a local variable with the same name as a global variable, it
is a completely different variable. This means that you can make it whatever type
you want. You should be careful, however, when declaring global and local vari-
ables that have the same name. Some programmers prefix all global variable names
with “g” (for example,gCountinstead of Count). This makes it clear in the source
code which variables are global and which are local.

Workshop ............................................................................................................


The Workshop provides quiz questions to help you solidify your understanding of the
material covered, and exercises to provide you with experience in using what you’ve
learned. The answers to the quiz are in Appendix F, “Answers.”

Quiz ..............................................................................................................


  1. What does scope refer to?

  2. What is the most important difference between local storage class and external
    storage class?

  3. How does the location of a variable definition affect its storage class?

  4. When defining a local variable, what are the two options for the variable’s life-
    time?

  5. Your program can initialize both automatic and static local variables when they are
    defined. When do the initializations take place?

  6. True or False: A register variable will always be placed in a register.


300 Day 12

19 448201x-CH12 8/13/02 11:17 AM Page 300

Free download pdf