Multi-character constant warnings

118,025

Solution 1

This warning is useful for programmers that would mistakenly write 'test' where they should have written "test".

This happen much more often than programmers that do actually want multi-char int constants.

Solution 2

If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:

-Wno-multichar

I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.

Solution 3

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).

Solution 4

Even if you're willing to look up what behavior your implementation defines, multi-character constants will still vary with endianness.

Better to use a (POD) struct { char[4] }; ... and then use a UDL like "WAVE"_4cc to easily construct instances of that class

Share:
118,025
Mircea Ispas
Author by

Mircea Ispas

Updated on January 12, 2020

Comments

  • Mircea Ispas
    Mircea Ispas over 4 years

    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 variables with same value. When parsing wave/tiff/other file types is more clear to compare the read values with some 'EVAW', 'data', etc instead of their corresponding values.

    Sample code:

    int waveHeader = 'EVAW';
    

    Why does this give a warning?