Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Math Order of Operation

So I know that C++ has an Operator Precedence and that

int x = ++i + i++;

is undefined because pre++ and post++ are at the same level and thus there is no way to tell which one will get calculated first. But what I was wondering is if

int i = 1/2/3;

is undefined. The reason I ask is because there are multiple ways to look at that (1/2)/3 OR 1/(2/3). My guess is that it is a undefined behavior but I would like to confirm it.

like image 356
Caesar Avatar asked Jul 02 '12 15:07

Caesar


3 Answers

If you look at the C++ operator precedence and associativity, you'll see that the division operator is Left-to-right associative, which means this will be evaluated as (1/2)/3, since:

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. For example, the expression a=b=c is parsed as a=(b=c), and not as (a=b)=c because of right-to-left associativity.

like image 87
Reed Copsey Avatar answered Oct 05 '22 23:10

Reed Copsey


In your example the compiler is free to evaluate "1" "2" and "3" in any order it likes, and then apply the divisions left to right.

It's the same for the i++ + i++ example. It can evaluate the i++'s in any order and that's where the problem lies.

It's not that the function's precedence isn't defined, it's that the order of evaluation of its arguments is.

like image 28
jcoder Avatar answered Oct 05 '22 23:10

jcoder


The first code snippet is undefined behaviour because variable i is being modified multiple times inbetween sequence points.

The second code snippet is defined behaviour and is equivalent to:

int i = (1 / 2) / 3;

as operator / has left-to-right associativity.

like image 28
hmjd Avatar answered Oct 06 '22 01:10

hmjd