-1

Why the below is difference?

program001.c:

int main (void)  
{ 
    int a=3,*p,x;
    p=&a;       
    *p++;
    x=*p
    printf("a=%d, *p=%d, x=%d\n",a, *p, x);
    return 0;
}

result: a=3,*p=21974,x=21974

Program002.c:

int main (void)  
{ 
    int a=3,*p,x;
    p=&a;       
    x=*p++; 
    printf("a=%d,*p=%d,x=%d\n",a,*p,x);
    return 0;
}

result:a=3,*p=3,x=3

for program001's result, it can be understand: *p++ is point to undefined value, so it is unreasonable result.

for program002's result, why it is not equal to program001?

Jens
  • 69,818
  • 15
  • 125
  • 179
Zhen Zhou
  • 1
  • 2
  • Please look up operator precedence and associativity – Ed Heal Oct 04 '17 at 15:13
  • Think about when the increment happen in relation to the assignment to `x`. Also consider the difference between `*p++` and `*++p`. – Some programmer dude Oct 04 '17 at 15:13
  • 5
    Also think about *where* `p` is pointing after it has been incremented, and learn about [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior). – Some programmer dude Oct 04 '17 at 15:15
  • @Someprogrammerdude: Judging from OP's comment about program001's result, it seems to me he has already thought about where `p` is pointing and about the consequences of undefined behavior. – Dolda2000 Oct 04 '17 at 15:26
  • What logic did take you to the conclusion that the results will be the same? Because it is an UB, there is no expected program output – 0___________ Oct 04 '17 at 16:06

2 Answers2

4

From example 1:

*p++;
x=*p;

can be rewritten as

*p;    // dereference p and ignore the value. Valid as p points to a
p++;   // increment p
x=*p;  // dereference p and assign the value to x. Invalid as p no longer
       // points to an int object

From example 2:

x = *p++;

can be rewritten as

x = *p;    // dereference p and assign the value to x.  Valid as p points to a
p++;       // increment p

So in example 1 you assign to x after p is incremented. In example 2 you assign to x before p is incremented.

Both examples has undefined behaviour, e.g. due to *p in the print statement where p is dereferenced even though it doesn't point to a int object anymore as p was incremented. In example 1 the undefined behavior already happens at x=*p;

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
0

From the point of the behavior of the two programs, there is no difference. Both programs have Undefined Behavior on all control paths. So both programs can crash, can halt, can run infinitely, can print anything or not print anything at all.

bolov
  • 72,283
  • 15
  • 145
  • 224