Multi-character constant warnings

前端 未结 6 1507
别那么骄傲
别那么骄傲 2020-11-22 09:26

Why is this a warning? I think there are many cases when is more clear to use multi-char int constants instead of \"no meaning\" numbers or instead of defining const variabl

6条回答
  •  一整个雨季
    2020-11-22 10:08

    Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:

    int x = *(int*)"abcd";
    

    Or a bit more specific:

    int x = *(int32_t*)"abcd";
    

    One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):

    int x = ((union {char s[5]; int number;}){"abcd"}).number;
    
    /* just a demo check: */
    printf("x=%d stored %s byte first\n", x, x==0x61626364 ? "MSB":"LSB");
    

    Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).

提交回复
热议问题