Search code examples
c++c++11narrowing

Narrowing conversion from char to uint8_t


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.


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.