Question

I want to assign a char with a char literal, but it's a special character say 255 or 13.
I know that I can assign my char with a literal int that will be cast to a char: char a = 13;
I also know that Microsoft will let me use the hex code as a char literal: char a = '\xd'

I want to know if there's a way to do this that gcc supports also.

Was it helpful?

Solution 2

The hexidecimal escape sequence is not specific to Microsoft. It's part of C/C++: http://en.cppreference.com/w/cpp/language/escape

Meaning that to assign a hexidecimal number to a char, this is cross platform code:

char a = '\xD';

The question already demonstrates assigning a decimal number to a char:

char a = 13;

And octal numbers can also be assigned as well, with only the escape switch:

char a = '\023';

Incidentally, '\0' is common in C/C++ to represent the null-character (independent of platform). '\0' is not a special character that can be escaped. That's actually invoking the octal escape sequence.

OTHER TIPS

Writing something like

char ch = 13;

is mostly portable, to platforms on which the value 13 is the same thing as on your platform (which is all systems which uses the ASCII character set, which indeed is most systems today).

There may be platforms on which 13 can mean something else. However, using '\r' instead should always be portable, no matter the character encoding system.

Using other values, which does not have character literal equivalents, are not portable. And using values above 127 is even less portable, since then you're outside the ASCII table, and into the extended ASCII table, in which the letters can depend on the locale settings of the system. For example, western European and eastern European language settings will most likely have different characters in the 128 to 255 range.

If you want to use a byte which can contain just some binary data and not letters, instead of using char you might be wanting to use e.g. uint8_t, to tell other readers of your code that you're not using the variable for letters but for binary data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top