tags:

views:

80

answers:

2

Conside the following code:

int main()
{
    signed char a = 10;

    a  += a; // Line 5

    a = a + a;

    return 0;
}

I am getting this warning at Line 5:

d:\codes\operator cast\operator cast\test.cpp(5) : warning C4244: '+=' : conversion from 'int' to 'signed char', possible loss of data

Does this mean that += operator makes an implicit cast of the right hand operator to int?

P.S: I am using Visual studio 2005

Edit: This issue occurs only when the warning level is set to 4

+8  A: 

What you are seeing is the result of integral promotion.

Integral promotion is applied to both arguments to most binary expressions involving integer types. This means that anything of integer type that is narrower than an int is promoted to an int (or possibly unsigned int) before the operation is performed.

This means that a += a is performed as an int calculation but because the result is stored back into a which is a char the result has to undergo a narrowing conversion, hence the warning.

Charles Bailey
Integral promotion should happen only if needed. In this case, it's clearly not. The standard says 'An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int [...]' It never says it should, or will, just it can (i.e. if needed)
PierreBdR
@PierreBdR: 5.17 says `A += B` is equivalent to `A = A + B`; 5.7 (additive operators) says that the usual arithmetic conversions are performed; 5/9 says that this means that integral promotions are performed on both sides, so yes, integral promotion is required in this case.
Charles Bailey
A: 

Really, there shouldn't be any warning for this line. the operator += is very well defined for all basic types. I would place that as a small bug of VC++ 2005.

PierreBdR