2

The following piece of code compiles and runs with gcc version 4.7.2 (Debian 4.7.2-5) :

#include <stdio.h>

int main()
{
    const volatile x = 3;
    volatile const y = 4;

    return 0;
}

Should I assume that the order of const and volatile is irrelevant? I tried reading up here : encpp ref and it doesn't say anything about the order(or I'm missing it?)

baibo
  • 448
  • 4
  • 20

1 Answers1

4

Yes, the order is irrelevant. In C++, the relevant specification is in 7.1p1, decl-specifier and decl-specifier-seq, which basically explain that there is a sequence of relevant keywords, and 7.1.6, which lists const and volatile as two these keywords. Note that the production is weird enough that these are valid as well, though in the interest of readability I would strongly recommend against them:

const int volatile a = 1;
volatile int const b = 2;
const int volatile typedef vcint; // defines vcint to be an alias for const volatile int
Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
  • 1
    The same thing holds for all of the keywords in the decl-specifier: things like `unsigned const int volatile long static x = 10;` are perfectly legal. (C has deprecated the use of the storage class specifier other than in the initial position.) For readability, of course, one should be consistent, and one should not break up multi-word type names (e.g. `unsigned long int`). (The preferred order would put the cv-qualifiers at the end, e.g. `int const volatile x = 1;`) – James Kanze Jun 20 '14 at 10:38
  • Agree with everything except the religious point at the end ;-) – Sebastian Redl Jun 20 '14 at 10:41
  • It was in parentheses for a reason:-). I do think that there is a consensus for 1) storage class specifiers at the beginning, 2) not breaking up the complete type name and 3) within the type name, signed/unsigned modifier precedes length modifier (`long`, `short`) precedes basic type (`int`, `float`, `double`). It also seems acceptable, at least in most places, to leave out the `int` _if_ there are other type modifiers, e.g. `unsigned`, `long`. As for putting the cv-qualifiers after... you usually have to, so you might as well be consistent. – James Kanze Jun 20 '14 at 12:37