7

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?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46

4 Answers4

7

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.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
4

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
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • More info: the difference between this and `const int a, b, c;` is that `static` (along with `extern`, `typedef`, `auto` and `register`) is a *storage class specifier*, whereas `const` (and `volatile` and `restrict`) are *qualifiers* . The grammar rules are different for specifiers than for qualifiers. – M.M Jul 11 '14 at 04:09
  • "The grammar rules are different for specifiers than for qualifiers." so how about `static volatile int a, b, c;`. Will `a`, `b` and `c` all end up the same? – Andy J Jul 12 '17 at 06:18
1

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

Sorcrer
  • 1,634
  • 1
  • 14
  • 27
1
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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Anand
  • 621
  • 3
  • 9
  • 31