2

I was wondering whether the const/static keywords apply to all variables declared in a single C++ statement.

For instance, with this code

static const int a, b, c;

are they all declared as static const ints? Or is just 'a' declared as a static const int and the rest declared as an int or some variation of that?

Nate Rubin
  • 752
  • 1
  • 7
  • 12

1 Answers1

8

static and const are applied to all variables.

*, [], & are applied only to a single variable.

E.g.:

static int *a, &b=*a, c[10]={};
  • All variables are static, BUT

  • Only a is a pointer,

  • Only b is a reference,

  • Only c is an array.

For details on variable declaration syntax, see:

See also this question if you're interested why the syntax is the way it is.

Community
  • 1
  • 1
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
  • I would up-vote this if you supplied a source for your statement. – Joshua D. Boyd Jul 08 '13 at 18:38
  • @JoshuaD.Boyd: the statement I provided is syntactically correct (it compiles), but it won't run since I initialize a reference by some pointer which points to a random memory location. It produces a segmentation violation or the like. I just wanted to provide a minimal example of the stuff, that's why... – Alex Shesterov Jul 08 '13 at 18:48
  • By a source, I meant in the citation sense (outside authoritative documentation of source sort), not in the supply source code sense. – Joshua D. Boyd Jul 08 '13 at 18:51
  • 1
    Rule of thumb: Everything that could be written left of the actual data type (`int` etc.) modifies that data type and consequently applies to everything declared. Everything else modifies the variable and thus applies only to one variable. But I agree that declarations in C can produce a knot in your brain... – cmaster - reinstate monica Jul 08 '13 at 19:03
  • @JoshuaD.Boyd: oh, that's an excellent point; I've added a few links - though it may not be what you've expected, but this is what I found interesting related to the issue. – Alex Shesterov Jul 08 '13 at 19:19
  • Thanks, thats just the sort of thing I was suggesting. – Joshua D. Boyd Jul 08 '13 at 23:28