1

I have a program which is giving different output on different compiler.

#include<stdio.h>
int main()
{
char arr[] = "abcdef";
char *p = arr;
while(*p != '\0')
{
    char b = *p;
    *p++ = *(p+1);
    *p++ = b;
}    
printf(" %s", arr);
getchar();
return 0;
}

When I am compiling this using gcc compiler it gives output "badcfe". But when using other compiler, it is giving "caec". Can someone please help me out how does it has two different outputs (with explanation).

Jay
  • 207
  • 2
  • 12

1 Answers1

4

*p++ = *(p+1) would be evaluated as *(p++) = *(p+1) due to operator precedence.

The behaviour of this entire expression is undefined since you are reading and writing to p in an unsequenced step. So the compiler is allowed to do anything it wants when it encounters this expression, which accounts for the difference in the output that you are observing.

The "undefinedness" is similar to the undressed i = i++; for an integral type i.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483