Question

Compiling the following snippet using C++11(demo here):

#include <stdint.h>

int main() {
    const uint8_t foo[] = {
        '\xf2'
    };
}

Will trigger a warning(at least on GCC 4.7), indicating that there's a narrowing conversion when converting '\xf2' to uint8_t.

Why is this? sizeof(char) is always 1, which should be the same as sizeof(uint8_t), shouldn't it?

Note that when using other char literals such as '\x02', there's no warning.

Was it helpful?

Solution

Although char doesn't necessarily have to be 8-bits long, that's not the problem here. You are converting from signed char to unsigned (uint8_t), that's the reason for the error.

This:

const int8_t foo[] = {
    '\xf2'
};

will compile fine.

OTHER TIPS

Looking at my system, the constant \xf2 is overflowing, since it's out of range of a signed char. It's being represented as -14 which is then implicitly converted to an unsigned int, giving a value of 4294967282. That's then narrowed to a char, producing this warning:

warning: narrowing conversion of ‘'\37777777762'’

Using (unsigned char)'\xf2' removes the warning.

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