c++在while条件下声明和测试变量

c++ declaring and testing variable in while condition

本文关键字:测试 变量 声明 条件下 while c++      更新时间:2023-10-16

在下面的代码段中,执行流从不进入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  )