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

ID: Q121290

1.50 1.51 WINDOWS kbtool kbbuglist

The information in this article applies to:

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:

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

Last Reviewed: July 23, 1997