开发者

Implicit conversion while using += operator?

Conside开发者_C百科 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜