2

Consider the below program

#include <stdio.h>
void main(){
    int p = -8;
    int i = (p++, ++p);
    printf("%d\n", i);
}

I am unable to get why the output is -6.

p++ would increment after the assignment statement is executed, ++p will increment before thereby making -8 to -7.

How i is assigned -6?

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
user3767495
  • 129
  • 3

3 Answers3

6

Because for a comma operator A,B then A is done first then B, and p++ increment the p, and ++p also increment the p. Operator precedence.

Or think like this

int i = (p++, ++p);

is

p++;
int i = ++p;
Kindred
  • 1,229
  • 14
  • 41
4

The expression (p++, ++p) has a comma operator. The comma operator evaluates its operand left-to-right and yields the result of the right most operand. Thus i gets the value -6 (after p++ and ++p operations).

P.P
  • 117,907
  • 20
  • 175
  • 238
2

as ptr_user7813604 said, you are using the comma operator which is a binary operator in c. It evaluates it's first operand (in your case p++ increments p) and then discards the result (meaning p was incremented but not assigned to any variable) and then it evaluates the second operand (in your case ++p increments p) and returns this value and type. because the second operand is ++p so you receive the value after it was incremented, if the second operand was another p++ you would have assigned to i the value before it was incremented.

for additional information about the comma operator you can look up https://en.wikipedia.org/wiki/Comma_operator.

Yaya
  • 87
  • 9