Auto, Register, Static, mutable, extern in C++

8 篇文章 0 订阅

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 autostaticregisterextern, 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() { #Ej@(283  
int i = 5; // auto integer NDDe`8{7V  
float f = 34.56; // auto float MHg+6C9Sx  
char buf[80]; // auto character array L$x 1k/v  
struct complex { :0,J|BO|  
float imag, real; FeVDif&  
} val; // auto structure 2G_iHS  
i++; // increment i .Wn_^"  
f++; // increment f "O]AH  
. . . ]' cG+s  
}

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) { P
L4v-M  
int cnt; // auto count variable @#rSg  
for (int i = 0; i < max; i++) // loop over array O,o4/7 21  
if (a[i] == val) // found value? wKN(Nt#  
cnt++; // increment count NER "_w:  
return cnt; // return count >A F/Y  
} 7O7<Az(I  

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():

  void itoh(unsigned int n) { >>U&-:  
  int digit; 5xpf: Lz  
  static const char *hex = "0123456789abcdef"; !(8B 'i7  
4$*Rx+5-  
  if ((digit = n / 16) != 0) %}IT3LeM  
    itoh(digit);           // recursive call v88@".xx|<  
  cout << hex[n % 16]; 2"%Lj7Z&  
}

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

 { 	FNg8/C=k  
static const char buf[] = "fountain"; E# B!ntu,  
static struct complex { B:EBctP  
float real, imag; ;#Kt@[A:  
} value = { 2.3, 1.7 }; Y8-A[U  
}

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 "|B!xjy  
long fellow; // program scope - any module may access it HM-<zm  
vTt]6qt  
void f() // program scope - any module may call it _&xXnrFL  
{ pv8O$eA  
. . . ]&+V @]W  
} *@caV./=  
JG/7o"4  
static void g() // file scope - only this module may call it 5K{ P$$  
{ #lreK5  
. . . ld;E/](r  
}

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) { pGVro&R&  
for (register int i = 0; i < huge; i++) !NF- >{>  
. . . a[i] . . . `.aBk31:  
}

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++) .JB9"5V  
for (register int j = 0; j < jmax; j++) ^LBqd)O  
. . . 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; mq/{N?B  
register int i; gS#TPQ>m  
for (i = 0; i < imax; i++) 1-~D"+NN  
for (j = 0; j < jmax; j++) bD5aTa/  
. . . 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 pRoS
  
#include <iostream.h> G5A1^p*/9  
#include "global.h" "!Rttv@  
G /wOU  
int nitems; 0h0~I4+  
double servo[100]; S(wt4`In  
something s; WZT8{P8|5  
double f(); U= H3L  
7=8y- g}  
int main() dx JM*>  
{ Hrg+t*;= C  
. . . *MB_BmXu  
servo[5] = f(); vAf?*K  
. . . bfvd%w*  
}

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 MS+/PR  
#include <iostream.h> +96]s8)8hQ  
#include "global.h" AOUZ66F@  
extern int nitems; ip 1s*  
extern double servo[]; |(4H  
o) 3C  
double f() vJe/8x*  
{ 5,gg%Q.ya1  
extern something s; DMy 1V)R  
. . . Wr0q)HFIt  
}

Module mod2.C uses extern to declare nitemsservo, 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 { Gne6)  
mutable Type data_member; // data member is modifiable &k9E%uyb  
. . . // for constant structures smV K~/*Nl  
};

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 { dC(t	sQ5  
int data; // integer data u,pq/+b  
node *fwd; // pointer to next node cgES7&k.w  
mutable node *last; // pointer to last node accessed n[r-fw  
node *find_node(int) const; // constant member function )L5-8  
}; /t}Daj  
x|2w+%E  
node *access(const node *list, int d) $4ww[B'7  
{ j[9,>fS  
return list->find_node(d); )?rD>[  
}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值