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+= packedCou开发者_开发百科nt
, 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
}
As far as the compilers are concerned
iCount += packedCount;
iCount = iCount + packedCount;
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:
#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
}
printf("iCount after the inner loop: %d\n", iCount); /* DEBUG */
printf("packedCount after the inner loop: %d\n", packedCount); /* DEBUG */
//iCount+= packedCount; //this produces 8 for 0+packedCount
//this works
iCount= iCount+packedCount; //skip the next byte in array, since it was already packed
printf("iCount after update: %d\n", iCount); /* DEBUG */
}
精彩评论