Search code examples
c++visual-studiovisual-c++lvalue

Why this code is generating error C2105 instead of C3892?


IDE: MS Visual studio 2008 Version 9.0.21022.8 RTM

Compiler: Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86

Code:

// main.cpp - compiled as cpp file
int main()
{
 const int x = 10;
 x++; // error C2105: '++' needs l-value
 x = x+1; // error C3892: 'x' : you cannot assign to a variable that is const
 return(0);
}

What l-value is compiler expecting to throw error C2105?


Solution

  • x is an lvalue, so the diagnostic message is misleading.

    This is a quality of implementation issue, i.e. a bug.

    Whatever routine that detects the const is mangled up with the routine that checks for the expression x in your x++ not being an rvalue.

    The end result is the same! So it's unlikely that anyone hugely cares. You could raise this issue on Microsoft Connect and see whether it goes anywhere, but you should probably test your code on newer versions first, since 2008 was rather a long time ago.

    For what it's worth, I get the same result in Visual Studio 2012 Express; Intellisense clarifies that it's a "modifiable lvalue" that it's hoping for:

    Screenshot of the result in VS2012