PRB: Post-Incrementation May Differ if Compiling with /qc

ID Number: Q81886

6.00 6.00a 6.00ax 7.00 | 6.00 6.00a

MS-DOS | OS/2

Summary:

SYMPTOMS

Post-incrementation sometimes gives different results when

compiled with Microsoft C versions 6.0, 6.0a, and 6.0ax in code

where the precedence of that operation over others is undefined

by the ANSI standard depending on whether it is compiled with

the /qc option on or off. This also occurs with Microsoft C/C++

version 7.0 depending on whether the /f or /f- switch is used.

Microsoft C may also differ from QuickC in this respect.

The symptoms resulting from the differences in generated code may

be difficult to determine because a variety of effects can be

produced. In general, if code compiled with and without the /qc

option generates different results, ambiguous precedence involving

post-incrementation may be the cause. For example, code may work as

desired when compiled with /qc, and corrupt memory when compiled

without /qc, if pointers are being post-incremented.

Note that this discussion also applies to pre-incrementation,

pre-decrementation, and post-decrementation.

CAUSE

Section 3.3 of the ANSI draft states that:

Between the previous and next sequence point an object shall

have its stored value modified at most once by the evaluation

of an expression. Furthermore, the prior value shall be accessed

only to determine the value to be stored (31).

.

.

.

(31) This paragraph renders undefined statement expressions

such as

i = ++i + 1;

while allowing

i = i + 1;

Therefore, the behavior is implementation-dependent, and will vary

from compiler to compiler.

When the Microsoft C compiler is invoked with the /qc option, it

actually calls a separate compiler, which handles ambiguous

precedence involving post-incrementation differently than the

optimizing compiler.

RESOLUTION

Generally, code should be written so as not to be ambiguous by the

ANSI standard. This ensures that the code is portable to any ANSI C

compiler.

If it is not possible to eliminate the ambiguous code, then it must

be compiled with the compiler that gives the desired result.

More Information:

The following line of code can be used to demonstrate how the

implementations differ:

for ( i=0; array[i] != '\0'; ptr[i]=array[i++] );

If compiled with /qc or QuickC, it is evaluated as if it were:

for ( i=0; array[i] != '\0'; ptr[i+1]=array[i], i++ );

If compiled without /qc, it is evaluated as if it were:

for ( i=0; array[i] != '\0'; ptr[i]=array[i], i++ );

Additional reference words: 6.00 6.00a 6.00ax 7.00