c++在while条件下声明和测试变量
c++ declaring and testing variable in while condition
在下面的代码段中,执行流从不进入while语句条件和ndx1总是0,原因是什么?
while( int ndx1 = 10 && (ndx1 > 0) )
{
// some statements
ndx1--;
}
语句
while( int ndx1 = 10 && (ndx1 > 0) )
等价于
while( int ndx1 = ( 10 && (ndx1 > 0) ) )
这是表达式(ndx1
声明中使用的初始化式)
( 10 && (ndx1 > 0) )
使用未初始化的变量ndx1
本身,其值不确定。因此,程序行为是未定义的。
短路与(&&
)具有比赋值(=
)更高的优先级,因此您将ndx1
赋值给包含ndx1
的表达式10 && (ndx1 > 0)
。这是未定义的行为,因为ndx1
在第一次迭代时尚未初始化。偶然情况下,在第一次迭代时它很可能为零,因此10 && (ndx1 > 0)
的求值为false,将其赋值给ndx1
,并且while条件失败,因此永远不会进入循环。
见http://en.cppreference.com/w/cpp/language/operator_precedence .
while( int ndx1 = 10 && (ndx1 > 0) )
被解释为:
while( int ndx1 = (10 && (ndx1 > 0)) )
由于ndx1
是在初始化之前使用的,因此会受到未定义行为的影响。
for
循环将更适合您的需要。
for( int ndx1 = 10; ndx1 > 0; --ndx1 )
相关文章:
- 如何在提升构建中设置环境变量以进行提升单元测试框架?
- 使用 gtest 框架在单元测试代码中检查目标对象的私有变量的最佳实践是什么?
- 在 gtests 中测试C++全局变量的最佳方法
- 如何对私有变量是否已更改进行单元测试
- 在命名空间中定义变量,但在测试中获取空值
- 测试适用于成员变量的成员函数
- C++ / GoogleTest - 如何测试正在测试的类的成员变量
- 单元测试呼叫实例变量的函数
- 如果需要测试,则C 将常数变量放在CC文件中
- 单元测试一个变量的true和false
- 我可以测试变量是否已使用 new 或 malloc 分配吗?
- 对同一变量的测试结果似乎不同
- C++在测试成员变量是否等于NULL时冻结
- QT 测试 - 变量/对象失去价值
- 这段代码有什么问题?如果变量是字母,我无法测试名为数字的变量
- Xcode C++全局变量的单元测试
- 在谷歌测试中访问受保护的变量
- Google使用SetUpTestCase静态变量测试未定义的引用
- 访问私有变量的单元测试
- c++在while条件下声明和测试变量