0

I'm wondering if someone can help explain why the following code snippet returns a and b both equal to 6.

int main(){
    int a =5, b;
    a++,b=a;

    printf("%d %d\n", a, b);
}

Is the answer that, in fact, the behaviour is implementation-specific (based on compiler)? Or, is the following the explanation (my understanding of postfix is that the incrementing only happens after the variable a has been "used" by whatever other operator exists around it). In this case, is the a "used" by the comma operator when the LHS is evaluated and then thrown away, such that incrementing happens before the RHS is evaluated?

Thanks in advance!

EE18
  • 109
  • 1
  • `,` allows first part to be evaluated first, then second part: https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do behaviour is specified by the standard – Jean-François Fabre Dec 01 '19 at 20:29
  • There is no notion of "use" with respect to this. The term you're looking for is "sequence points". – Mat Dec 01 '19 at 20:30
  • I would avoid writing code like `a++,b=a;`. Putting the two statements on their own lines will make it easier to read and maintain. You no longer have to stop and figure out what the effects are. – Dave S Dec 01 '19 at 20:33
  • @Mat thanks for letting me know. After a quick peek at wikipedia, it seems to say that there is a sequence point between the two evaluations of the comma operator? – EE18 Dec 01 '19 at 20:35
  • @Dave You are absolutely right. This snippet is more for pedagogical purposes. – EE18 Dec 01 '19 at 20:36
  • It's equivalent to `a++;b=a;`. It's also equivalent to `b = ++a;`, which is what I would use. – S.S. Anne Dec 01 '19 at 21:09

0 Answers0