Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion to std::array<unsigned char, 1ul>::value_type from int may alter its value

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?

like image 384
Mihai Todor Avatar asked Aug 20 '12 14:08

Mihai Todor


1 Answers

Am I doing something illegal here?

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).

Can it cause problems in certain scenarios?

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 |.

Why would the | produce an int?

Because all integer values are promoted before being used in arithmetic operations. If their type is smaller than int, then they are promoted to int. (There's somewhat more to promotion than that, but that's the rule that's relevant to this question).

like image 135
Mike Seymour Avatar answered Sep 22 '22 18:09

Mike Seymour