开发者

Is underscore allowed in case labels?

开发者 https://www.devze.com 2023-02-10 05:26 出处:网络
In some header file which I can not modify I have the following set of defines: #define FLAG1(0x0000_0001)

In some header file which I can not modify I have the following set of defines:

#define FLAG1                      (0x0000_0001)
#define FLAG2                      (0x0000_0002)
...

Then, in my code I use them in switch:

switch (aaa) {
    case FLAG1:
    ....

    case FLAG2:
    ....
}

As a result, Coverity reports on 2 defects per each case label:

RW.EXP_RPAREN: 
Event 开发者_运维知识库exp_rparen: expected a ")"

RW.CASE_LABEL_CONFLICT:
Event case_label_conflict: case label value has already appeared in 
this switch at line XX

What is wrong with these case labels? Does it violate C standards?


Yes, you are allowed to have parentheses. What you aren't allowed to have is a number like 0x0000_0001.

That's not a valid hex number, you'll probably have to remove the _ character.


Yeah, it's the underscore that's causing problems. FWIW, here are the relevant sections from the C language standard (draft n1256):

  • § 6.4.4.1 Integer Constants: defines the structure for integer constants and shows that _ is not a valid character for an integer constant;
  • § 6.6 Constant Expressions: defines the restrictions on constant expressions;
  • § 6.8.4.2 The switch statement: defines the restrictions on case labels in a switch statement.


It think it expects the ) when it finds the _ which isn't valid in hexadecimal notation.

The compiler should actually complain like this:

error: invalid suffix "_0001" on integer constant

case labels may well contain parentheses:

switch(number) {
    // no way to determine operator 
    // precedence without parens here
    case 2*(1+2):
}
0

精彩评论

暂无评论...
验证码 换一张
取 消