How am I supposed to write an unsigned char to a file without warnings?

OutputStream os;
os.writeByte (char (0xc0));

warning C4310: cast truncates constant value

os.writeByte (0xc0);

warning C4309: ‘argument’: truncation of constant value

Can we get functions that take unsigned values?

This doesn’t trigger a warning, and seems to give the same result:

os.writeByte ('\xc0')

Tested on Compiler Explorer.

Unfortunately that’s not portable, because char can be signed or unsigned depending on the implementation: https://godbolt.org/z/t9nLqu

Looks like x86-64 clang/gcc/msvc all agree that it’s signed, but gcc for 64-bit arm thinks char is unsigned.

In fact, on the x86-64 compilers, writeByte ('\xc0') is worse than implementation-defined, it’s undefined behaviour, because truncating a signed integer is UB. If you do this, your entire program is null and void.

Probably best to avoid char completely and to to use the int8_t and uint8_t types from <cstdint> if you want to write portable code.

2 Likes

Good to know! So, in answer to @Roland1, I guess another way to write an unsigned char to the stream would be to use the writeRepeatedByte() method. That takes a uint8 as the byte parameter.

os.writeRepeatedByte (0xc0, 1);
1 Like