Do not understand the calculation

advertisements

I have following C program, and I'm not understanding the output of the following program.

#include <stdio.h>

int main()
{
    int a,b, *p1, *p2, x,y,z;

    a=12;
    b=4;

    p1=&a;
    p2=&b;

    x=*p1 * *p2-6;
    y=4* - *p2 / *p1+10;

    printf("y=%d", y);

    return 0;
}

The output of the program is 9. But what is the meaning of 4*?


What is the meaning of 4*

The * there is the multiplication operator. Only one operand, 4, is shown in that extract. The full multiplication is:

4* - *p2

which is more clearly written as

4 * -(*p2)

Write out the expression, substituting the values. We can ignore x since it is not used. Which leaves us:

y= 4* - *p2 / *p1+10;

And *p2 is b which is 4. And *p1 is a which is 12. So the expression is:

y = 4 * -4 / 12 + 10;

And this evaluates as:

y = ((4 * -4) / 12) + 10;

Which is

y = (-16 / 12) + 10;

Which is

y = -1 + 10;