Duplicate const qualifier allowed in C but not in C++?

前端 未结 4 443
不知归路
不知归路 2020-12-03 13:35

Sample code snippet

const const const int x = 10;   
int main()
{}

gets compiled in C but not in C++. Why does it get compiled in C? I thou

相关标签:
4条回答
  • 2020-12-03 14:03

    C++ 2003 prohibits it in 7.1.5/1 "... redundant cv-qualifiers are prohibited except when introduced through the use of typedefs or template type arguments ...".

    0 讨论(0)
  • 2020-12-03 14:08

    C99 §6.7.3/4:

    If the same qualifier appears more than once in the same specifier-qualifier-list, either directly or via one or more typedef s, the behavior is the same as if it appeared only once.

    Yes, that is valid C99, and your discovery is correct.

    0 讨论(0)
  • 2020-12-03 14:14

    From the last C++0x draft, [dcl.type]:

    As a general rule, at most one type-specifier is allowed in the complete decl-specifier-seq of a declaration or in a type-specifier-seq or trailing-type-specifier-seq. The only exceptions to this rule are the following:

    — const can be combined with any type specifier except itself.

    — volatile can be combined with any type specifier except itself.

    — signed or unsigned can be combined with char, long, short, or int.

    — short or long can be combined with int.

    — long can be combined with double.

    — long can be combined with long.

    0 讨论(0)
  • 2020-12-03 14:24

    The C++0x grammar appears to allow it:

    cv-qualifier-seq:

    • cv-qualifier cv-qualifier-seq opt

    cv-qualifier:

      const
    
      volatile
    

    Also, [decl.type.cv] appears to allow it:

    There are two cv-qualifiers, const and volatile. If a cv-qualifier appears in a decl-specifier-seq, the init-declarator-list of the declaration shall not be empty. [ Note: 3.9.3 and 8.3.5 describe how cv-qualifiers affect object and function types. — end note ] Redundant cv-qualifications are ignored. [ Note: For example, these could be introduced by typedefs. — end note ]

    0 讨论(0)
提交回复
热议问题