-1

Please explain to me how th3 output is 11.

int main(){
    int delta = 12, alpha = 5, a = 0;
    a = delta - 6 + alpha++;
    printf("%d", a);

    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    `a = 12 - 6 + 5`? If it was `++alpha`, it would be 12. – Neil Oct 22 '22 at 04:19
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Oct 22 '22 at 05:23
  • Does this answer your question? [What is the difference between prefix and postfix operators?](https://stackoverflow.com/questions/7031326/what-is-the-difference-between-prefix-and-postfix-operators) – Caleb Oct 22 '22 at 05:45

2 Answers2

3

In C, putting ++ after a variable in an expression increments it after the expression is evaluated. Therefore, substituting the variables for their values, it would be a = 12 - 6 + 5, and afterwards alpha would be equal to 6.

If you put ++ before the variable, it increments it before the expression is evaluated. So therefore, if you had done a = delta - 6 + ++alpha, it would have been 12.

tsoa
  • 131
  • 7
0

The result of x++ is the current value of x - as a side effect, x is incremented. Logically, your expression is equivalent to writing

tmp = alpha;
a = delta - 6 + tmp;
alpha = alpha + 1;

with the caveat that the assignment to a and the update to alpha can occur in any order, even simultaneously. Point is that a is computed with the value of alpha before the increment. Now, your specific compiler may choose to generate code like

a = delta - 6 + alpha;
alpha = alpha + 1;

because that makes sense here, but the point is that it isn't specified exactly when the side effect to alpha is applied.

The result of ++x is the current value of x plus one - as a side effect, x is incremented. Had you used ++alpha in your statement, it would logically equivalent to writing

tmp = alpha + 1;
a = delta - 6 + tmp;
alpha = alpha + 1;

with the same caveat as above. a is computed with the value of alpha + 1. Again, your compiler may choose to generate code equivalent to

alpha = alpha + 1;
a = delta - 6 + alpha;

or it could have done something like

a = delta - 6 + (alpha + 1);
alpha = alpha + 1;

Again, it isn't specified exactly when the side effect is applied.

John Bode
  • 119,563
  • 19
  • 122
  • 198