Home > OS >  C Code Algebraic output is not what I thought
C Code Algebraic output is not what I thought

Time:10-23

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;
}

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related