3

Why is this allowed:

uint32_t x = 'name';

But this gets truncated to 32 bits:

uint64_t x = 'namename';

Is there a way to have an 8-byte long multicharacter literal?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Charles W
  • 2,262
  • 3
  • 25
  • 38
  • I don't recognize this kind of syntax. how could you compile a string with character syntax? – David Haim Sep 30 '15 at 14:37
  • It compiles correctly, but I don't see the use case of this code! – rkachach Sep 30 '15 at 14:39
  • 4
    @DavidHaim: `'name'` is not a string literal, it's a character literal, specifically a *multicharacter literal*. It's of type `int` and has an implementation-defined value. It's not a particularly useful language feature. – Keith Thompson Sep 30 '15 at 14:57
  • [C++ multicharacter literal](https://stackoverflow.com/q/3960954/995714), [What do single quotes do in C++ when used on multiple characters?](https://stackoverflow.com/q/7459939/995714) – phuclv Aug 31 '18 at 04:52

2 Answers2

7

Yes, as long as your compiler has 8-byte ints and supports it.

The C++ standard is farily terse regarding multi-character literals. This is all it has to say on the matter (C++14, 2.14.3/1):

An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal, or an ordinary character literal containing a single c-char not representable in the execution character set, is conditionally-supported, has type int, and has an implementation-defined value.

(Emphasis mine)

As you see, pretty much all the standard says is that if multicharacter literals are supported (they don't have to be), they are of type int. The value is up to the compiler.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
0

If only 4 byte multi-character literats are supported, you could use:

uint64_t x = (((uint64_t)'abcd') << 32) + 'efgh';

but it would probably end up as 2 literals.

rcgldr
  • 27,407
  • 3
  • 36
  • 61