Reputation: 121
I am currently learning C Programming ( my first programming language ). I am a little bit confused with the operators precedence. Arithmetic operators precedence are as follows.
*
/
%
+
-
This is what is given in my book at least. What i am confused is about how do i go solving expressions when it comes to my theory exams ? I tried solving many expressing with the order given above but fail to get a correct answer.
Given the following definitions:
int a = 10, b = 20, c;
How would we solve this expression?
a + 4/6 * 6/2
This is an example in my book.
Upvotes: 1
Views: 2151
Reputation: 60721
a + 4/6 * 6/2
= 10 + 4/6 * 6/2
= 10 + 0*6/2
= 10 + 0/2
= 10
Note that 4/6
evaluates to 0
as integer division is used.
Upvotes: 4
Reputation: 133122
The precedence of /
and *
is the same in C, just as it is in mathematics. The problem is that in mathematics the following expressions are equivalent, whereas in C they might not be:
(a/b) * (c/d)
(a/b*c) / d
These aren't equivalent in C because if a
, b
, c
, and d
are integers, the /
operator means integer division (it yields only the integral part of the result).
For example,
(7/2)*(4/5); //yelds 0, because 4/5 == 0
(7/2*4)/5; //yields 2
A general good coding practice is being explicit about your intentions. In particular, parenthesize when in doubt. And sometimes even when you're not.
Upvotes: 4