0

I can define literal numbers in C and C++ with the help of suffix L, U, D, etc like this:

34656345L
94375804U
3.141593F
...

So in the expression they appear the compiler knows their types. Is the a similar way to define 1-byte literal numbers like char? I know I could use (char)28 for example, but probably there's a suffix I haven't found.

I have had a look at this page http://www.cplusplus.com/doc/tutorial/constants/ but no char constants mentioned there.

Zereges
  • 5,139
  • 1
  • 25
  • 49
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95

2 Answers2

3

There is no suffix for character literals.

In C++, you can use '-enclosed literals like '\x9f' (in C they are ints), but there is no way to specify a decimal character code this way.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Thank you. Is there a complete source where it is said so that I could take a loot at and read more about suffixes? – Fomalhaut Aug 24 '19 at 17:11
  • @Fomalhaut Check https://en.cppreference.com (I think there are several separate pages on different kinds of liteals: integers, reals, ...). It's one of the best C++ resources around. – HolyBlackCat Aug 24 '19 at 17:19
2

In C++, char{28} does what you want. There is no suffix for char (nor for unsigned char) literals.

As @JesperJuhl reminds us, you can create your own suffix for char literals, if you so desire, like so:

constexpr char operator "" _c(int i) { return char{i}; }

and then you could write 123_c which would have type char. But - I wouldn't recommend it, it'd probably mostly confuse people.


PS: You can use character literals such as 'a' or 'b' (which would have values 97 and 98 respectively if your compiler uses an ASCII-compatible character set, e.g. UTF-8 or Latin-1). These will have a char type, not an int type. See discussion here.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 3
    You could always [make your own](https://en.cppreference.com/w/cpp/language/user_literal) suffix - if you so desire ;) – Jesper Juhl Aug 24 '19 at 17:21