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

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
Issue type :
Technology :

Last Reviewed: December 22, 1999 © 2001 Microsoft Corporation. All rights reserved. Terms of Use.