Weird conversion warning

G

Guest

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;
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?
 
T

Tamas Demjen

Josué Andrade Gomes said:
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;
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?


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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top