The -Wconversion GCC parameter produces the warning from the title when compiling this program:
#include <iostream>
#include <array>
#include <string>
int main ()
{
std::string test = "1";
std::array<unsigned char, 1> byteArray;
byteArray[0] = byteArray[0] | test[0];
return 0;
}
Here is how I compile it: g++- -Wall -Wextra -Wconversion -pedantic -std=c++0x test.cpp and I’m using GCC 4.5.
Am I doing something illegal here? Can it cause problems in certain scenarios? Why would the | produce an int?
You’re converting from a signed type to an unsigned type. If the signed value were negative, then the unsigned result would be an implmentation-defined non-negative value (and therefore not the same as the initial value).
Only if the value might be negative. That might be the case on somewhat exotic architectures where
sizeof (char) == sizeof (int), or if your code were doing something more complicated than combining two values with|.Because all integer values are promoted before being used in arithmetic operations. If their type is smaller than
int, then they are promoted toint. (There’s somewhat more to promotion than that, but that’s the rule that’s relevant to this question).