Imnoob - 1 year ago 79
C Question

Associativity of operators in C

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.

``````#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);
}
else
{
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.

Both multiplicative `*` and `/` are left-to-right operators. They even have the same precedence.
``````d = (10 / 100) * p
Since `10 / 100` is an integer division with the result `0`, hopefully now you can see the difference.