-->

Why can't the static and register storage clas

2020-03-26 05:15发布

问题:

When defining a variable in the following manner:

static register int a1 = 0;

we get the error:

error: multiple storage classes in declaration specifiers

Is there any fundamental reason for this error? Why can't a variable be both stored in a register, and also be initialized only at start up/first call? It is possible to attach the register storage class to a global variable. <- edit: not true

回答1:

If a compiler implemented what you wanted faithfully then it would tie up a CPU register for the length of your program. That's hardly practical.

Remember that register is only advisory.



回答2:

The standard does not allow use of more than one storage-class specifier in a declaration.

From the C99 Standard:

6.7.1 Storage-class specifiers

1 storage-class-specifier:

typedef
extern
static
auto
register

2 At most, one storage-class specifier may be given in the declaration specifiers in a declaration.



回答3:

The main reason is that the register qualifier implies that the variable has automatic storage duration. It is basically an auto variable for which you are telling the compiler that it would be good to place in a General Purpose CPU register.

static qualifier implies a static or thread storage duration.

Obviously the two are incompatible if applied to the same variable!

It would be like asking to have a variable that die and survive (at the same time) when the activation record it belongs is removed.