Microsoft KB Archive/88434

= INFO: Casting Difference Between C and C++ May Cause C2105 =

Article ID: 88434

Article Last Modified on 7/5/2005

-

APPLIES TO


 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 1.5 Professional Edition
 * Microsoft Visual C++ 2.0 Professional Edition
 * Microsoft Visual C++ 2.1
 * Microsoft Visual C++ 4.0 Standard Edition
 * Microsoft Visual C++ 5.0 Enterprise Edition
 * Microsoft Visual C++ 5.0 Professional Edition

-



This article was previously published under Q88434



SUMMARY
In C++, the result of a cast to a reference type is an lvalue; casts to any other type are not lvalues. This is explicitly stated in the &quot;C++ Annotated Reference Manual,&quot; by Ellis and Stroustrup, on page 69. In a .C file, explicit casting to any data type may result in an lvalue only if Microsoft language extensions are enabled. The same error is generated in a .C file if Microsoft extensions are disabled.

This difference can cause problems in code that compiles without error using a C compiler. The sample code below illustrates this with a simple increment of a casted result. If it is compiled as a C source file, no errors are generated (although using warning level 4 generates &quot;C4213: nonstandard extension used : cast on l-value&quot;). However, if it is compiled as a C++ source file, the following error is generated:

error C2105: '++' needs lvalue

Microsoft C/C++ does provide a mechanism for achieving this by implementing a cast to a reference that achieves the same effect: ++(long*&)p;

Sample Code
/* Compile options needed: none

void main {  char *p;

((long *)p)++;  // If the file is saved as a .CPP, this }                  // causes an error.

Keywords: kbinfo kblangcpp kblangc kbcode KB88434

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.