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

Function does not get called if the output does not matter

本文关键字:调用 函数 输出 无关紧要 如果      更新时间:2023-10-16

我有以下代码:

#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,那么无论其余调用返回什么,"changed"变量都将始终为true。我不在乎,我希望它保持"真实",这毕竟是正确的。但我的观点是,剩下的四个调用可能已经将"bar"变量更改为完全不同的值,我需要在循环后使用这个"正确更改"的值。

有人能解释一下吗,为什么仅仅因为函数的返回值不相关就不调用它?因为我看不出这意味着函数中的代码也不相关,尤其是当一些参数通过非常数引用传递时。(据我所知,该功能甚至可能完全终止程序。)

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

我用VS2015编译了这个,标准的DEBUG和RELEASE模式有同样错误的结果。

显然,如果我去掉"changed"变量,只调用循环中的函数,我会得到正确的输出。

这是由于短路评估。

标准状态(强调矿):

5.15逻辑OR运算符

|不同,||保证从左到右评价此外,如果第一个操作数的求值结果为true,则不求值第二个操作数。

尝试交换参数:

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