Imnoob Imnoob - 1 year ago 75
C Question

Associativity of operators in C

Please read it before making it duplicate.

From the book which I have read:
Associativity can be of two types:

1-Left to Right

Left to Right associativity means that the left operand must be unambiguous.Unambiguous in what sense? It must not be involved in evaluation of any other sub-expression.

2-Right to left

same as above.
Now please read the following code:

#include <stdio.h>

/* no of item purchased>1000 then discount of 10% else full price */
int main()
int n;
float r,p,d,t;

printf("Enter the no of item purchased");
scanf("%d", &n);

printf("Enter the price per item");
scanf("%f", &r);

if(n > 1000)
p = n * r;
printf("Price before discount = %f\n", p);

d = 10 / 100 * p; //please have a carefull look at d
printf("discount offered is = %f\n", d);

t = p - d;
printf("total price after discount = %f\n", t);
p = n * r;
printf("total price is = %f", p);

return 0;

As given in above code "d=10/100*p" it follows L-->R associativity as p is calculated previously involved in evaluation of other expression.

Now changing the d "d=p*10/100" this case correctly calculates the discount but above one gives zero as answer.
Can anyone please explain associativity in context to above example.

Answer Source

Both multiplicative * and / are left-to-right operators. They even have the same precedence.

Therefore, your expressions can be re-written like so without changing their meaning:

d = (10 / 100) * p
d = (p * 10) / 100

Since 10 / 100 is an integer division with the result 0, hopefully now you can see the difference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download