A Problem with the Compiler

I have a simple test program like this:

#include

int main(void)
{
int a[4] = {3,4,5,6};
int *p = a;
int i;

for(i=0; i<4; i++)
*p++ = *p + 10;

for(i=0; i<4; i++)
printf(“a[%d]=%d\n”, i, a_);

printf(“a=%p, a+4=%p, p=%p\n”, a, a+4, p);

return 0;
}

When I use pgcc 10.8-0 to compile and run it, I got this output:

a[0]=3
a[1]=14
a[2]=15
a[3]=16
a=0xbfabc7dc, a+4=0xbfabc7ec, p=0xbfabc7f6

a[0] isn’t incremented. But when I use GCC to compile and run it, I got the correct output:

a[0]=13
a[1]=14
a[2]=15
a[3]=16
a=0xbf89c1ac, a+4=0xbf89c1bc, p=0xbf89c1bc

I think it’s a bug in PGCC compiler._

Hi Hush,

All bets are off since with this code since the statement “*p++ = *p + 10;” will result in undefined behaviour. Since the order in which the left or right side evaluations are performed it is up to the implementer which “p” you’re using and your results will vary by compiler and platform.

See: http://c-faq.com/expr/seqpoints.html

The fix is to break this into two lines:

$ cat test1.c 
int main(void)
{
int a[4] = {3,4,5,6};
int *p = a;
int i;

for(i=0; i<4; i++) {
  *p = *p + 10;
   p++;
}

for(i=0; i<4; i++)
printf("a[%d]=%d\n", i, a[i]);

printf("a=%p, a+4=%p, p=%p\n", a, a+4, p);

return 0;
} 
$ pgcc test1.c -fast
$ a.out
a[0]=13
a[1]=14
a[2]=15
a[3]=16
a=0x7fff1241d2a0, a+4=0x7fff1241d2b0, p=0x7fff1241d2b0

Hope this helps,
Mat