Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

3.4 Storage Classes

Program variables have a storage class in addition to a data type. Storage classes are important in C++ for several reasons. One, they tell the compiler how to create and release variables and where to place them in the run-time environment (stack, data area, or CPU registers). Two, storage class specifiers affect the initial values and the scope of variables. This section reviews the storage class specifiers auto, static, register, extern, and mutable.

auto

The default storage class specifier auto (short for automatic) allocates memory for variables from the run-time stack. The definition

 auto int num; 

for example, compiles in C++, although the keyword auto is optional and seldom used. Automatic definitions appear inside functions and blocks and have undefined initial values. Furthermore, their scope applies only to the block in which they are declared. The following function, for example, creates four automatic variables, all of different data types.

 void subr() {
  int i = 5;             // auto integer
  float f = 34.56;          // auto float
  char buf[80];            // auto character array
  struct complex {
    float imag, real;
  } val;               // auto structure
  i++;                // increment i
  f++;                // increment f
  . . .
 }

The compiler allocates stack memory for each auto variable every time a program calls subr(). Likewise, the compiler releases this stack memory when the function returns. Even though subr() increments i and f, they continue to receive their initial values every time we call the function. This implies that automatic variables do not retain their values between function calls or after exiting a block and reentering it again.

NOTE

Always initialize auto variables before you use them. Although many C++ compilers issue warnings if you don't, the following example is a common error.

 int count(int a[], int max, int val) {
  int cnt;               // auto count variable
  for (int i = 0; i < max; i++)    // loop over array
    if (a[i] == val)         // found value?
     cnt++;             // increment count
  return cnt;             // return count
 }
 

The count() function loops over an array of integers and returns the number of elements that are equal to a certain value. The cnt variable, however, does not have an initial value (is it 0 or something else?). The behavior of this function is not predictable (it may work fine or return a random value).

static

The storage class specifier static allocates memory from the data area. The definition

 static int num; 

makes the variable num reside in the data area and retain its value throughout program execution. Variables that you declare static receive their initial values (0 if you don't provide one) before execution of main(). C++ has two types of static variables. A variable is internal static (the first type) if its definition appears inside a block with the keyword static. To illustrate, let's modify the recursive function itoh() from earlier in this chapter (see Listing 3.3 on page 91).

 void itoh(unsigned int n) {
  int digit;
  static const char *hex = "0123456789abcdef";

  if ((digit = n / 16) != 0)
    itoh(digit);           // recursive call
  cout << hex[n % 16];
 }

Every time a recursive function calls itself, a new set of automatic variables appears on the run-time stack. This is fine for variables that we modify (auto variable digit, for example), because recursive calls must have access to separate copies of their local, nonstatic variables (otherwise, recursive algorithms typically won't work). The pointer variable hex, however, does not need to be automatic because we do not modify it in itoh() (we use it only as an rvalue). When we declare hex as static, the compiler places one pointer in the data area (shared by all recursive calls), and we improve performance.

Internal statics also provide an efficient way to initialize automatic arrays and structures. For example, the statements

 {
  static const char buf[] = "fountain";
  static struct complex {
    float real, imag;
  } value = { 2.3, 1.7 };
 }

initialize an array buf and structure value inside a block. Variable buf contains the string "fountain", and value contains the floating point numbers 2.3 and 1.7, organized as a structure of type complex.

NOTE

If possible, use internal statics to initialize arrays and structures inside blocks and functions. Using internal statics creates a single instance of the structure or array, whose values persist across block or function execution. Although C++ compilers do not require static here, its use is generally more efficient. Why? A compiler that allows initializations of nonstatic arrays and structures inside blocks and functions must generate assembly code or call routines to initialize all the elements (as well as provide defaults for the uninitialized elements). This initialization happens every time you call the function. The use of static to initialize your arrays and structures once at load time improves performance.

The second type of static variable (called external static) applies to separately compiled modules (files of function and variable definitions). External static definitions appear outside blocks with the keyword static. Here are several examples.

 static char coal;     // file scope - only this module may access it
 long fellow;        // program scope - any module may access it

 void f()          // program scope - any module may call it
 {
  . . .
 }

 static void g()      // file scope - only this module may call it
 {
  . . .
 }

The variable fellow and function f() have program scope, which means any module may call f() or access fellow (this makes them global). The character coal and function g(), on the other hand, have file scope (modules outside this file cannot call g() or access coal).

Note that a variable defined outside a function lives in the data area and the word static affects only its scope. Inside a function, the word static does not affect a variable's scope, only its storage class.

NOTE

Use unnamed namespaces instead of external static to create variables with file scope (see "Unnamed Namespaces" on page 137). External static is deprecated in ANSI C++.

register

The storage class specifier register stores a variable's data in a hardware CPU register (if available) instead of memory. For example, the definition

 register int num; 

uses a register for the integer num. Only nonstatic, local variables may reside in registers, and C++ uses the same rules for register variable scope and initialization as it does with automatic variables. You cannot take the address of a register with &, use static with registers, or declare register variables outside of functions.

NOTE

Register variables are highly machine and compiler dependent. Many compilers, for instance, allocate registers for only pointers, int, and char data types. Furthermore, your compiler may choose to ignore all of your register declarations or give you a register even if you don't ask for one! Consult your compiler's documentation to see how to use register variables effectively.

Why use register variables? In time-critical code, register variables can improve a program's performance. Arithmetic and array subscripting operations inside loops usually execute faster with register variables than with auto or static variables. Loop variables, pointers, and function parameters are also suitable candidates for register variables. Registers are a limited resource, so you'll want to allocate them carefully. When the compiler runs out of hardware CPU registers, variables that you declare register become automatic.

The following code, for example, uses a register variable to loop through a large array if it's time to process data.

 if (process) {
  for (register int i = 0; i < huge; i++)
    . . . a[i] . . .
 }

Inside the for loop, the program declares i as a register variable before it loops through the array. If a register is available, the loop executes faster than it would without one.

NOTE

What should you do when there are not enough registers? If this situation arises, declare your registers outside of loops and declare the most important register variables first. This approach makes the least important variables become local variables if the compiler cannot provide registers.

A good application of this technique is with multidimensional array subscripts. The following code, for example, loops through all the elements of a two-dimensional array of integers declared as b[imax][jmax].

 for (register int i = 0; i < imax; i++)
   for (register int j = 0; j < jmax; j++)
    . . . b[i][j] . . .

The compiler, however, is likely to allocate a register first for i, not j (if only one register is available). The following approach is arguably better and more portable for time-critical code.

 register int j;
 register int i;
 for (i = 0; i < imax; i++)
  for (j = 0; j < jmax; j++)
    . . . b[i][j] . . .

Since the second for loop executes more often than the first for loop, it's more important for the compiler to provide a register for j than for i.

extern

The storage class specifier extern allows modules to access global variables (program scope) and non-static functions defined in another module. The declaration

 extern int num; 

for example, makes the integer num (defined elsewhere) accessible in the module that contains this declaration. The compiler does not allocate memory with extern declarations, and you must supply a data type after extern.

Suppose, for example, file mod1.C calls a function whose definition appears in file mod2.C, which, in turn, accesses variables defined in mod1.C. Here's the code for mod1.C.

Listing 3.11 Defining external variables

 // mod1.C
 #include <iostream.h>
 #include "global.h"

 int nitems;
 double servo[100];
 something s;
 double f();

 int main()
 {
  . . .
  servo[5] = f();
  . . .
 }

Module mod1.C calls a function f() and defines an integer (nitems), an array of 100 doubles (servo), and a structure (s), whose type definition (something) appears in global.h. These variables will be available to mod2.C because we do not define them as static.

Here's the code for mod2.C.

Listing 3.12 Declaring external variables

 // mod2.C
 #include <iostream.h>
 #include "global.h"
 extern int nitems;
 extern double servo[];

 double f()
 {
  extern something s;
  . . .
 }

Module mod2.C uses extern to declare nitems, servo, and s (defined in mod1.C). You may place extern statements anywhere a declaration is legal, as long as the extern declaration appears before you use the variable in a statement or expression. Note that the compiler ignores the size in an extern array declaration (such as servo[100]).

Likewise, the extern specifier in function prototypes is optional, since it is the default storage class. C++ allows

 extern double f(); 

in mod1.C, although it's not necessary. Without the keyword static, all function declarations are external by default.

mutable

The storage class specifier mutable applies to structure and class data members. Here is the format for structures (classes (page 177) have the same format).

 struct struct_name {
  mutable Type data_member;    // data member is modifiable
  . . .              // for constant structures
 };

Mutable means "subject to change or alteration." The mutable keyword allows constant member functions to modify mutable data members of constant structures and objects. (See "Const Member Functions" on page 193.) Why would one need mutable? Consider this example with structures.

 struct node {
  int data;           // integer data
  node *fwd;          // pointer to next node
  mutable node *last;      // pointer to last node accessed
  node *find_node(int) const;  // constant member function
 };

 node *access(const node *list, int d)
 {
  return list->find_node(d);
 }

Each node in a linked list has an integer and a pointer to another node. The find_node() member function searches the list for an integer and returns a pointer to the node that contains it. For efficiency, suppose find_node() "remembers" the last node it accesses from the list and stores its node pointer in data member last. As a constant member function, find_node() does not modify a node's data member nor its fwd pointer, but find_node() does need to modify data member last. When we declare last mutable, functions like access() may call find_node() with constant lists and still have it update data member last properly.

We examine mutable with class objects in "Mutable Data Members" on page 194.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020