Static Variable Declaration (C)

三世轮回 提交于 2019-12-09 17:29:42

问题


Are the following two static variable declarations equivalent?

1.

    static int var1;
    static int var2;
    static int var3;

2.

    static int var1, var2, var3;

More specifically, in case 2, will all variables be static, or just var1?


回答1:


Yes the declarations in case 1 and 2 are identical. We can see this by going to the draft C99 standard section 6.7.5 Declarators which says (emphasis mine going forward):

Each declarator declares one identifier, and asserts that when an operand of the same form as the declarator appears in an expression, it designates a function or object with the scope, storage duration, and type indicated by the declaration specifiers.

We can see the grammar from section 6.7 Declarations is as follows:

declaration:
   declaration-specifiers init-declarator-listopt ;

the declaration-specifiers include storage duration:

declaration-specifiers:
   storage-class-specifier declaration-specifiersopt

so the storage duration specifier applies to all the declarators in the init-declarator-list which has the following grammar:

init-declarator-list:
   init-declarator
   init-declarator-list , init-declarator
init-declarator:
   declarator
   declarator = initializer

You may wonder about pointers, they are handled handled differently and we can see this from the grammar in 6.7.5 for declarators:

declarator:
    pointeropt direct-declarator
[...]
pointer:
    * type-qualifier-listopt
    * type-qualifier-listopt pointer



回答2:


They're equivalent.

In case 2, all the variables will be static.

The storage class specifier static applies to all the declared variables in the declaration.




回答3:


You've just shown how variables can be declared differently.

 static int var1, var2, var3;

or

static int var1;
static int var2;
static int var3;

has the same meaning

ie; a variable of same data type(and also of same storage class) can be declared individually or all together once




回答4:


static int var1, var2, var3;

is equivalent to:

static int var1;
static int var2;
static int var3;

case 1 or case 2 both are used for readability purpose but meaning is same.



来源:https://stackoverflow.com/questions/24658907/static-variable-declaration-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!