0

Any reason for the following aberration?

Consider the following C program (named PstFixInc.c)

#include <stdio.h>
int main (int argc, char *argv [])
{
  int num = 0;
  num = (num++) % 4;
  printf ("num: %d\n",num);
  return 0;
}

If compiled with gcc 4.8.1:

gcc -o PstFix.exe PstFixInc.c

and then executed, you get the result:

num: 0

If compiled with Microsoft (R) C/C++ Optimizing Compiler Version 18.00.21005.1 for x86

cl PstFixInc.c

and then executed, you get the result:

num: 1

tavmem
  • 19
  • 3

3 Answers3

4

This is undefined behavior.

You're assigning to the same variable twice without an interleaving sequence point.

Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
4

What you have is undefined behavior, you are modifying num and using its previous value other than to determine the value to be stored within the same sequence point. This is covered in the draft C99 standard section 6.5 paragraph 2 which says:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored.73)

There are also two examples of undefined behavior:

i = ++i + 1;
a[i++] = i;

The first one is pretty similar to your example. Using clang even gives you a nice warning:

 warning: multiple unsequenced modifications to 'num' [-Wunsequenced]
  num = (num++) % 4;
  ~     ^
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • It seems that improved diagnostics that directly reference the source code is one of the primary benefits of clang (vs. GCC). – tavmem Jul 25 '14 at 15:00
0

This line:

num = (num++) % 4;

is undefined behavior per the C standard. Any result that the code produces is "correct".

wolfPack88
  • 4,163
  • 4
  • 32
  • 47