BUG: Incorrect Code Generated When Use ? : with ++

Last reviewed: July 22, 1997
Article ID: Q121290
1.50 1.51 WINDOWS kbtool kbbuglist

The information in this article applies to:

  • Microsoft C/C++ Compiler (CL.EXE), included with Microsoft Visual C++ for Windows, versions 1.5 and 1.51

SYMPTOMS

Compiling code that uses the ternary conditional operator (? :) with the increment operator (++) may generate incorrect code. The variable to which the increment operator is applied will never be incremented. The sample routine below demonstrates this problem. The problem occurs only with the fast compiler when using default compiler optimizations.

The problem does not occur in Microsoft Visual C++, 32-bit edition, versions 1.0 or 2.0.

CAUSE

The code generated by the compiler loads the variable value into a register, increments the variable itself, and then incorrectly stores the original value from the register back into the original variable location.

RESOLUTION

Use either of these workarounds:

  • Replace the conditional operator with an equivalent if-else statement. See the sample code shown in the More Information section below.

          -or-
    
  • Use the optimizing compiler. For example, compile the program with:

    cl /f- bug.c

STATUS

Microsoft has confirmed this to be a bug in the Microsoft products listed at the beginning of this article. We are researching this bug and will post new information here in the Microsoft Knowledge Base as it becomes available.

MORE INFORMATION

Sample Code to Illustrate the Bug

/*
    bug.c
    Compile options needed: NONE
*/

#include <stdio.h>
int  ccc = 0;

void main(void)
{
  int   i;
  for (i = 0; i < 20; i++)
  {
     ccc = (ccc < 3) ? ccc++ : 0;  // line 1
//   if (ccc <3) ccc++;            // replace line 1 with
//   else ccc=0;                   // these two to fix the problem

   printf("%d ", ccc);
  }
}


Additional reference words: 1.50 1.51 buglist1.50 buglist1.51
KBCategory: kbtool kbbuglist
KBSubCategory: CodeGen
Keywords : kb16bitonly


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: July 22, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.