c++ - 如果输出无关紧要,则不会调用函数

标签 c++ function optimization

我有以下代码:

#include <iostream> 

bool function(int a, int b, int &foo) {
    std::cout << "I have been called and I";
    if (a > b)// some magic that maybe changes 'foo'
    {
        foo++;
        std::cout << " did change the variable" << std::endl;
        return true;//inform that i have changed the value
    }
    std::cout << " did NOT change the variable" << std::endl;

    return false;
};

int main()
{
    bool changed = false;
    int bar = 0;
    for (size_t i = 0; i < 10; i++)
    {
        changed = changed || function(i,4,bar);
    }
    std::cout << "Bar:" << bar;
    std::cin.get();
    std::cin.get();
    return 0;
}

我有一个函数,它对两个变量做了一些魔法,这取决于它可能会改变 foo 变量。无论是否更改,它都会返回 bool 值。

假设我把这个函数放在一个循环中。我调用了它 10 次,我想知道这些调用中是否有任何一个改变了变量。 所以我对上面代码的期望是:

I have been called and I did NOT change the variable
I have been called and I did NOT change the variable
I have been called and I did NOT change the variable
I have been called and I did NOT change the variable
I have been called and I did NOT change the variable
I have been called and I did change the variable// 'changed' is now true
I have been called and I did change the variable
I have been called and I did change the variable
I have been called and I did change the variable
I have been called and I did change the variable
Bar:5

但是,没有。相反,我得到:

I have been called and I did NOT change the variable
I have been called and I did NOT change the variable
I have been called and I did NOT change the variable
I have been called and I did NOT change the variable
I have been called and I did NOT change the variable
I have been called and I did change the variable// 'changed' is now true
Bar:1

在第五次调用中,变量发生了变化,这是正确的。但是剩下的四个电话甚至都没有发生。我明白了,因为第五次调用返回 true,那么无论其余调用返回什么,“已更改”变量将始终为 true。我不关心那个,我希望它保持“真实”,毕竟这是正确的。但我的观点是,剩下的四个调用可能已将“bar”变量更改为完全不同的值,我需要在循环后使用这个“正确更改”的值。

那么有人可以解释一下吗,为什么仅仅因为它的返回值无关紧要就没有调用函数?因为我不明白这如何暗示函数内部的代码也是无关紧要的,尤其是当某些参数通过非常量引用传递时。(据我所知,该函数甚至可能完全终止程序。)

我不是在寻找解决方案,更像是解释为什么会发生这种情况。

我用 VS 2015、标准 DEBUG 和 RELEASE 模式编译了这个,结果相同。

显然,如果我消除“已更改”变量并仅在循环中调用该函数,我将获得正确的输出。

最佳答案

这是由于 short-circuit evaluation .

标准状态(强调我的):

5.15 Logical OR operator
...
Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

尝试交换参数:

changed = function(i,4,bar) || changed;

关于c++ - 如果输出无关紧要,则不会调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34501397/

相关文章:

c++ - 从 "cascading ifs"倍表达式中检索值

c++ - 用 C++ 编写取消操作背后的概念是什么?

javascript - Node.js 错误 "terminate called after throwing an instance of ' std::bad_alloc' what(): std::bad_alloc"

c++ - 在删除/释放优化函数调用之前不会进行空检查吗?

c++ - dlopen/etc 不编译。未解析的符号

javascript - JS : Higher Order Function Problem; Accept Array and Callback Function --> don't understand

list - 过滤掉列表列表中的空字符串

c - 如何在头文件和c文件中声明函数指针?

performance - 我可以完全优化吗?

python - 如何有效地将数据框中的条目映射到字典