C/C++ Math Order of Operation

后端 未结 5 1464
一生所求
一生所求 2020-12-11 19:10

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 t

相关标签:
5条回答
  • 2020-12-11 19:32

    It might be saying that it is undefined because you have chosen an int, which is the set of whole numbers. Try a double or float which include fractions.

    0 讨论(0)
  • 2020-12-11 19:34

    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.

    0 讨论(0)
  • 2020-12-11 19:40

    It is defined, it goes from left to right:

    #include <iostream>
    
    using namespace std;
    
    int main (int argc, char *argv[]) {
        int i = 16/2/2/2;
        cout<<i<<endl;
        return 0;
    }
    

    print "2" instead of 1 or 16.

    0 讨论(0)
  • 2020-12-11 19:44

    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.

    0 讨论(0)
  • 2020-12-11 19:49

    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.

    0 讨论(0)
提交回复
热议问题