Weird conversion warning

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Josué Andrade Gomes

    #1

    Weird conversion warning

    Take this code:
    1: int main()
    2: {
    3: unsigned short x[5] = { 1, 2, 3, 4, 5 };
    4: unsigned short sum = 0;
    5:
    6: for (int i = 0; i < 5; ++i) {
    7: sum += x[i];
    8: }
    9: }


    CL version 13.10.3077 gives the following warning:

    err.cpp(7) : warning C4244: '+=' : conversion from 'int' to 'unsigned
    short', possible loss of data

    Is this correct? Which possible loss of data the compiler is seeing here?






  • Tamas Demjen

    #2
    Re: Weird conversion warning

    Josué Andrade Gomes wrote:[color=blue]
    > Take this code:
    > 1: int main()
    > 2: {
    > 3: unsigned short x[5] = { 1, 2, 3, 4, 5 };
    > 4: unsigned short sum = 0;
    > 5:
    > 6: for (int i = 0; i < 5; ++i) {
    > 7: sum += x[i];
    > 8: }
    > 9: }
    >
    >
    > CL version 13.10.3077 gives the following warning:
    >
    > err.cpp(7) : warning C4244: '+=' : conversion from 'int' to 'unsigned
    > short', possible loss of data
    >
    > Is this correct? Which possible loss of data the compiler is seeing here?[/color]

    C++ compilers implicitly convert your unsigned short type into int for
    the addition operation ('+='). Generally speaking it's not a good idea
    to use types such as unsigned short, unless there's a tremendous amount
    of data, and you want to save memory and fetch time. However, for simple
    variables such as 'sum' and 'i' you should use int. The processor is not
    able to work with 16-bit or 8-bit numbers efficiently, the ALU can only
    work with 32-bit numbers. Every time you use an unsigned short, you have
    to know that the compiler will translate it into int every time you do
    anything (except assignment) to them.

    The warning is there because your code is compiled to something like this:

    for(int i = 0; i < 5; ++i)
    {
    int temp_x = x[i];
    int temp_sum = sum;
    temp_sum += temp_x;
    sum = temp_sum; // possible loss of data here
    }

    This is much less efficient than if you declared sum int or unsigned.

    Tom

    Comment

    Working...