C 中 while 条件后递减
我进行了搜索,但没有发现任何与我的查询相关的内容。 我当前正在调试 C 优化器,相关代码如下所示:
while( x-- )
array[x] = NULL;
在这种情况下应该发生什么?这个逻辑的结果应该在所有编译器中保持一致吗?
假设本例中 x 的初始值为 5。
问题是程序崩溃了,我的理解是它是由负数组元素引用引起的。
任何帮助将不胜感激。
I've done a search and I’ve found nothing relevant to my query.
I am currently debugging a C optimizer and the code in question looks like this:
while( x-- )
array[x] = NULL;
What should happen in this instance? And should the result of this logic be consistent across all compilers?
Lets say that the initial value of x in this case is 5.
The problem is that the program crashes, my understanding is that it is caused by a negative array element reference.
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此循环将以
x
等于-1
结束(假设x
有符号),但其主体不会产生对array 的访问[-1]
在最后一步。最后一个数组访问是array[0]
。该行为在所有实现中都是一致的。换句话说,您引用的代码中的负索引数组访问没有问题。但是,如果您尝试在循环后立即访问 array[x] ,那么您确实会访问 array[-1] 。
您引用的代码是一种相当著名的实现模式的变体,当需要使用无符号变量作为索引来向后迭代数组时使用。例如
,有时经验不足的程序员在向后迭代数组时会遇到使用无符号索引的问题。 (由于无符号变量永远不会有负值,因此将循环终止条件简单地实现为
x >= 0
是行不通的。)这种方法 - 即循环终止条件中的后递增 - 就是这样的在这种情况下有效。 (当然,它也适用于带符号的索引)。This cycle will end with
x
equal to-1
(assumingx
is signed), but its body will not produce access toarray[-1]
at the last step. The last array access is toarray[0]
. The behavior is consistent across all implementations.In other words, there's no problem with negative index array access in the code you quoted. But if you attempt to access
array[x]
immediately after the cycle, then you'll indeed accessarray[-1]
.The code you quoted is a variation of a fairly well-known implementational pattern used when one needs to iterate backwards over an array using an unsigned variable as an index. For example
Sometimes less-experienced programmers have trouble using unsigned indices when iterating backwards over an array. (Since unsigned variables never have negative values, a naive implementation of the cycle termination condition as
x >= 0
does not work.) This approach - i.e. post-increment in the cycle termination condition - is what works in such cases. (Of course, it works with signed indices as well).如果
x
的初始值为5,则会执行:如果
x
是有符号类型,那么x
的最终值为<代码>-1;否则,它将是该类型的最大值。If the initial value of
x
is 5, it will execute:If
x
is a signed type, then the final value ofx
will be-1
; otherwise, it will be the maximum value of the type.在处理
while
循环(前提条件)之前,请确保 x 为非负数。当进程离开
while
循环(后置条件)时,x
值也将为 -1。因此,离开while
循环后,不应使用x
作为索引来访问array
。Make sure
x
is non negative before processing thewhile
loop(precondition).Also
x
value will be -1 when the process leaves thewhile
loop(post condition). Therefore, after leavingwhile
loop, you should not access thearray
usingx
as index.