简体   繁体   中英

Ternary Operator And Addition Precedence

Could some explain how the following works, given the precedence table here: http://en.cppreference.com/w/cpp/language/operator_precedence

Given:

#include <cstdio>

#define MY_CONSTANT 5.6

int main(int argc, char ** argv) {
    const double calculatedValue = 4.4;
    const double myValue = MY_CONSTANT + 1 ? 4.4 : -4.4;

    printf("%f\n", myValue);
    return 1;
}

I expect

myValue == 10

I get

myValue == 4.4;
const double myValue = MY_CONSTANT + 1 ? 4.4 : -4.4;

is equivalent to:

const double myValue = (MY_CONSTANT + 1) ? 4.4 : -4.4;

Because ?: has lower precedance than + in C++ operator precedence table

Because (MY_CONSTANT + 1) evaluates to non-zero, myvalue is 4.4 .

To get 10 as output, you need explicit parenthesis to change the order of evaluation:

const double myValue = MY_CONSTANT + (1 ? 4.4 : -4.4);
//                                   ^              ^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM