0+= VARIABLE 如何产生 VARIABLE+1?
在更新用于计算 switch 语句变量的计数器时,我遇到了一个奇怪的错误。
int iCount
在循环外被赋值为零,它是用于 while 循环的计数器。
为了更新循环内的计数器,我编写了 iCount+= PackedCount
,在本例中,packedCount 为 7。然而,在调试器中,0+=packedCount 导致 PackedCount+1,即 8。这导致数组槽在整个循环中保持未填充状态。
当我将该行更改为 icount= PackedCount+iCount
时,返回了正确的值。
那么,这种行为是 C 所独有的吗?因为我经常在 Java 中这样做,没有出现奇怪的效果。
编辑 - 添加代码片段
#define SKIP 8
#define PACKED 7
int iCount;
iCount=0;
while (iCount < characters-1){
for (packedCount=iCount; packedCount< iCount+PACKED; packedCount++){
//ASCII compressor logic goes here
}
//iCount+= packedCount; //this produces 8 for 0+packedCount
//this works
iCount= iCount+packedCount; //skip the next byte in array, since it was already packed
}
I ran into a strange bug when updating a counter that is used to calculate the variable for a switch statement.
int iCount
was assigned zero outside of the loop, and it is the counter used for the while loop.
To update the counter inside the loop, I wrote iCount+= packedCount
, where packedCount was 7 in this case. In the debugger, however, 0+=packedCount resulted in packedCount+1, which was 8. That resulted in an array slot remaining unfilled throughout the loop.
When I changed the line to icount= packedCount+iCount
, the proper value was returned.
So, is this behavior unique to C, as I do this regularly in Java with no strange effects.
EDIT- Code snippet added
#define SKIP 8
#define PACKED 7
int iCount;
iCount=0;
while (iCount < characters-1){
for (packedCount=iCount; packedCount< iCount+PACKED; packedCount++){
//ASCII compressor logic goes here
}
//iCount+= packedCount; //this produces 8 for 0+packedCount
//this works
iCount= iCount+packedCount; //skip the next byte in array, since it was already packed
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就编译器而言
是相同的。如果它们产生不同的结果,那么代码中的某些内容会导致 iCount 被丢弃 - 也许是错误的指针引用。
As far as the compilers are concerned
are identical. If they're producing different results, then something in your code is causing iCount to get trashed - a bad pointer reference, perhaps.
试试这个,以及你能想到的其他变体:
Try this, and other variations you can think of: