Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;在while条件下声明和测试变量_C++ - Fatal编程技术网

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

C++ c++;在while条件下声明和测试变量,c++,C++,在下面的代码中,执行流永远不会进入while 条件和ndx1始终为0,原因是什么 while( int ndx1 = 10 && (ndx1 > 0) ) { // some statements ndx1--; } 线路 while( int ndx1 = 10 && (ndx1 > 0) ) 被解释为: while( int ndx1 = (10 && (ndx1 > 0)) ) 由于在初始化

在下面的代码中,执行流永远不会进入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
,因此会发生未定义的行为

for
循环将更好地满足您的需求

for( int ndx1 = 10; ndx1 > 0; --ndx1  )
短路和(
&&
)的优先级高于赋值(
=
),因此您将
ndx1
赋值给表达式
10&&(ndx1>0)
,该表达式包含
ndx1
。这是未定义的行为,因为在第一次迭代时,
ndx1
尚未初始化。由于偶然性,它在第一次迭代时可能为零,因此
10&(ndx1>0)
的计算结果为false,该值被分配给
ndx1
,while条件失败,因此从不进入循环

请参阅。

此声明

while( int ndx1 = 10 && (ndx1 > 0)   )
相当于

while( int ndx1 = ( 10 && (ndx1 > 0) )   )
这就是表达式(声明
ndx1
中使用的初始值设定项)


使用具有不确定值的未初始化variabel
ndx1
本身。因此,程序行为未定义。

编译时是否出现警告?int ndx1=0不是一个条件。您希望代码做什么?如果你写
ndx1=10
你会得到
ndx1
分配给
10
…是的,但是没有警告
int ndx1=10&&(ndx1>0)
是(可能)不变的,因此没有用。而且
(ndx1>0)
中的
ndx1
未定义。没有赋值。它是一个变量的声明,表达式用作初始值设定项。嗯,我想你可能是对的。但同样的优先规则也适用,不是吗?在声明的情况下,它不是赋值运算符,它不参与右侧的表达式。嗨,弗拉德,我正试图解决while循环的问题。我不是在寻找另一个for循环解决方案。谢谢你的解释!。如果你能编辑掉for循环,那就太好了。@knn你是什么意思?for循环是否妨碍了答案?@knn O;k我批准了您的更改。:)
( 10 && (ndx1 > 0) )