1

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

3
  • Well, I tested it with VS 2010 express, and it compiled with no warnings, so I think its some "undefined behavior"? Commented Jun 17, 2010 at 11:37
  • Set the warning level to 4 in the project settings under c/c++ general options. Commented Jun 17, 2010 at 11:39
  • With Level 4 still OK in VC++ 2010 Express Commented Jun 17, 2010 at 11:42

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.