Operator precedence in C++...

Explain the expression. 3/2*2.
compiler display a result 2.
How is it possible the result...
You are getting the number 2 because of how division is taking place before multiplication, because of how division is coming before multiplication because it comes first, read it from left to right. Not only that but because you are dividing integers the results will truncate towards zero.

3/2 * 2
3/2 = 1 (integer truncation towards zero)
1 * 2 = 2
With division and multiplication, whichever one comes first is evaluated first.

3 / 2 * 2
3 / 2 is 1.5
1.5 is truncated to 1
1 * 2 is 2
Last edited on
Hi rabster and boost lexical cast Thanks for your reply

I have one doubt. Compiler give first preference to multiplication after that division is working. But this example first division is working. How? Please explain..
The compiler does not prefer multiplication over division or vice versa. Between the 2, it is whichever one comes first.
Look at this table: http://en.cppreference.com/w/cpp/language/operator_precedence

As you can see multiplication and division have the same precedence.
3/2*2 is treated as (3/2)*2 because the associativity is left-to-right.
Last edited on
If multiplication would have higher precedence than division, then 3/2*2 would mean same as 3/(2*2), which equals 3/4 and results to 0.


PS. Not all operators have left-to-right associativity. Some, like assignment, are right to left.
Hi all
Thanks for your reply.. multiplication and division is same preference or not kindly explain..
Multiplication and division have the same precedence.
Hi all
Thanks for your valuable solution..
Topic archived. No new replies allowed.