如果输出无关紧要,则不会调用函数
Function does not get called if the output does not matter
我有以下代码:
#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;
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?