Arithmetic - Operator Precedence

Chapter chap3 section 4

The expressions

x+y*z and x*y+z

suffer from the same potential ambiguity as

x+y-z and x-y+z

however the problem is handled in a different way. The normal mathematical expectation is that multiplication is performed before addition. There are various ways of saying this, we could say that the "*" operator binds more tightly or we could say, and will say, that the "*" operator has a higher precedence than the "+" operator. Again a simple programming example confirms this point.

main()
{
	int	x=2,y=7,z=5;
	printf("The value of \"%d*%d+%d\" is %d\n",
			x,y,z,x*y+z);
	printf("The value of \"%d+%d*%d\" is %d\n",
			z,x,y,z+x*y);
}
resulting in the output
The value of "2*7+5" is 19
The value of "5+2*7" is 19
Of course, we could use parentheses if we actually wanted addition performed before multiplication as the following example shows.
main()
{
	int	x=2,y=7,z=5;
	printf("The value of \"%d*(%d+%d)\" is %d\n",
			x,y,z,x*(y+z));
	printf("The value of \"(%d+%d)*%d\" is %d\n",
			z,x,y,(z+x)*y);
}
resulting in the output
The value of "2*(7+5)" is 24
The value of "(5+2)*7" is 49


Operator Types