Search code examples
c++ccompiler-warningscompound-operator

C4244 level 4 warning on compound addition assignment, but not on sum and assignment


In MSVS 2005, The following C code generates one warning:

int main() {
    short a = 0;
    a += a; // C4244 (level 4)
    a = a + a; // OK
}

The warning message is:

warning C4244: '+=' : conversion from 'int' to 'short', possible loss of data

The same goes for C++ code.

What is the difference between the two statements? I have heard, but could not find any reference to any C or C++ standard, that the compound operator implicitly casts the right-hand expression to the left-hand side's type. But should the sum-and-assignment statement not do the same? I also suspected that it had to do with int promotion, but as I can see from the disassembly, this happens in both cases:

[...]
    a += a; // C4244 (level 4)
00411394  movsx       eax,word ptr [a] 
00411398  movsx       ecx,word ptr [a] 
0041139C  add         ecx,eax 
0041139E  mov         word ptr [a],cx 
    a = a + a; // OK
004113A2  movsx       eax,word ptr [a] 
004113A6  movsx       ecx,word ptr [a] 
004113AA  add         eax,ecx 
004113AC  mov         word ptr [a],ax 
[...]

Additionally, the warning does not appear in MSVS 2008 with warning level set to 4. So can I consider this a bug in VS 2005, that was fixed later, or is there some sense to the original warning? The documentation does not help me here.


Solution

  • It looks like a bogus warning.

    Warnings are supposed to warn you about code you wrote, not about intermediate operations.

    The code you wrote does not work with any int - only intermediate operations do.

    An inquiry about a case almost identical to yours in the Visual Studio Languages Forums is answered by Jonathan Caves - MSFT. His answer ends:

    "This is has been on our list of bugs to fix for quite a while - unfortunately we always find more "important" bugs to fix so we never get around to fixing this one - but someday we will."