Is there a compiler difference between an if-check and inline conditional?

时间:2017-06-13 20:41:13

标签: c++ if-statement g++ variable-assignment

I've recently begun using flags to handle an input loop's validity condition so it can be checked elsewhere inside the loop rather than having to redo the same check multiple times. However, I'm unsure how best to assign the flag. Is there a generally standard practice regarding this, or just personal style? What, differences are there in the compiled code, if any?

For example, instead of the following code:

bool isValidSize;

do {
    std::cout << "Enter the font size (8-12): ";
    std::cin >> fontSize;

    if (fontSize >= MIN_FONT_SIZE && fontSize <= MAX_FONT_SIZE) {
        isValidSize = true;
    } else {
        isValidSize = false;
        std::cout << "Invalid size. ";
    }
} while (!isValidSize);

the if-statement can be changed to make it more clear what isValidSize is set to at a glance:

    isValidSize = (fontSize >= MIN_FONT_SIZE && fontSize <= MAX_FONT_SIZE);
    if (!isValidSize) {
        std::cout << "Invalid size. ";
    }

Would this be compiled as an extra if-check? Is there any portability benefit to having the assignment separate from anything else? From just looking at the code, it seems the benefit of the first way is possibly only one branch but an additional assignment per rep and also has an else?

1 个答案:

答案 0 :(得分:1)

没有区别:proof

使用优化(GCC 6.3)在-O3上进行了测试。

选择您认为更具可读性的内容。