Function/Variable Scope   «Prev  Next»
Lesson 8 Storage classes
Objective Initializing external and static variables

C++ - Initializing Variables

Examine the default initializations of external and static variables.

In C++, both external variables and static variables are initialized to zero by the system if they are not explicitly initialized by the programmer. This includes arrays, strings, pointers, structures, and unions.
This means that
  1. for non-string arrays, each element is initialized to zero
  2. for strings, the string is initialized to a null string
  3. for structures and unions, each member is initialized to zero.

Automatic and register variables, however, usually are not initialized by the system. This means they can start with "garbage" values.

Including headers

Most libraries contain significant numbers of functions and variables. To save work and ensure consistency when making the external declarations for these items, C and C++ use a device called the header file. A header file is a file containing the external declarations for a library; it conventionally has a file name extension of 'h', such as headerfile.h.
(You may also see some older code using different extensions, such as .hxx or .hpp, but this is becoming rare.)
The programmer who creates the library provides the header file. To declare the functions and external variables in the library, the user simply includes the header file. To include a header file, use the #include preprocessor directive. This tells the preprocessor to open the named header file and insert its contents where the #include statement appears.
A #include may name a file in two ways:
  1. in angle brackets (< >) or
  2. in double quotes.

File names in angle brackets, such as:
#include < header>
cause the preprocessor to search for the file in a way that is particular to your implementation, but typically there is some kind of "include search path" that you specify in your environment or on the compiler command line. The mechanism for setting the search path varies between machines, operating systems, and C++ implementations, and may require some investigation on your part.
File names in double quotes, such as:
#include "local.h" tell the preprocessor to search for the file in (according to the specification) an implementation-defined way.
What this typically means is to search for the file relative to the current directory. If the file is not found, then the include directive is reprocessed as if it had angle brackets instead of quotes. To include the iostream header file, you write:
#include <iostream>
The preprocessor will find the iostream header file (often in a subdirectory called "include") and insert it.