Hacker News new | ask | show | jobs
by kps 4847 days ago

    int x = 'FOO!';
will not make demons fly out of your nose: it is not undefined behaviour. It is guaranteed to produce a value; the specific value is implementation defined (that is, one that the compiler vendor has decided and documented), but it is an integer value, not a demon value.

I'm sure, though, that someone sooner or later will be bitten by code like

    int x = 'é';
which is equally implementation-defined.
2 comments

On big-endian machines, the order of characters is preserved. Because of that, I've noticed this trick used in old network/protocol code where the intent was to use integer values in binary headers while maintaining easy readability if you are look at hex/ascii side-by-side. e.g.,

int x = 'RIFF';

.. if you were packing a WAVE file header.

The potential big advantage of this construct is that you can use it in switch() statements, which you can't do with strings. But it's probably better to use enum values, because the implementation-definedness removes the potential great advantage of this technique (that you can serialize these multicharacter literals nicely; consider SMTP implementations looking for 'HELO', 'MAIL', etc.).
It was pretty common in classic Mac OS and PalmOS for writing OStype constants. I vaguely remember that for some time gcc did different things with this construct depending on whether target OS was MacOS/PalmOS or anything else.

    int x = 'A';
is also implementation-defined.