-5

OK for Linux 32/64 Windows 32/64 compiled with GCC, DOS and OS2 with MS compiler on Mac OS o BSD compiled with GCC, go to infinity loop

char *b,p[]={'0','1','2','3','4','5','6','7','8','9','\0'};
for (b=p;(*(b++)=*b););
printf("p=%s\n",p);

// result:
// 123456789

// Test for MacOS or BSD
unsigned char Test=0x0F;
for (b=p;((*(b++)=*b) && --Test););
if (!Test) printf("Error\n");


// OK for Mac OS or FreeBSD
for (b=p;(*b);b++) *b=*(b+1);
printf("p=%s\n",p);

// result:
// 123456789

ok, now it works, but the question remains, why it does not work if the syntax is correct?

Blindonet
  • 1
  • 1
  • 2
    syntax != logic. And please clarify what the program is supposed to do, what the expected output is and what the actual output is. "it works" and "it does not work" isn't exactly descriptive. – kaylum Oct 03 '16 at 22:16
  • is part of a string processing routines, the routines works perfectly, properly tested on different operating systems, 32bit ubuntu, mint 64, Windows XP, Seven 64-bit as well as for pure whim of DOS and OS2. as evidenced on BDS like never ending loop, checked by inserting a counter to force the exit. – Blindonet Oct 03 '16 at 22:24
  • For C code in particular, there can be a **BIG** gap between "syntactically correct" and "it works". Something like `printf("2 + 2 = 5");` is perfectly good syntax. – Keith Thompson Oct 03 '16 at 22:28
  • ok, we see the expressive form. the routine properly plays the role assigned in the mentioned operating systems, while Mac enters into infinite loop. – Blindonet Oct 03 '16 at 22:35

1 Answers1

6

The problem is that this expression is unsequenced:

*(b++)=*b

Essentially, the value being modified is accessed more than once without a sequence point in between. This means that the behavior is undefined.

Your other expression is free of undefined behavior, because modification happens in the loop header:

*b=*(b+1)
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • exactly, in fact I entered the correction, but I would like to understand why. – Blindonet Oct 03 '16 at 22:39
  • @Blindonet The reason the standard requires a sequence point there is that it wants to give compiler makers a choice as to when exactly the side effect of `++` is to be applied. It can be applied before the assignment or after the assignment, which will either make your program work the way you expect or to break. – Sergey Kalinichenko Oct 03 '16 at 22:58