why this for loop goes in infinite loop executation?
see i have one code like this
int main () {
uint32_t i ;
for(i=4;i>=0;i--)
printf("i is %d \n",i);
return 0;
}
it goes in infinite loop. why i's va开发者_Python百科lue goes below 0 & still loop is going to executive?
uint32_t
means unsigned integer and so its value is always >= 0 - thus your loop executes infinitely.
Note that many compilers will issue a warning indicating that i>=0
comparison is always true.
You see negatives values in your printf
because you print it as %d
, but in the condition, the uint32_t
is always positive (you are doing an overflow).
You are using uint32_t means unsigned and then checking the condition in for loop that i >= 0 so when the loop executes for value i = 0 and then it makes the i = -1 but i is unsigned so it will make the value of i INT_MAX(what ever your system supports). so and still the value is greater than 0 so condition is true.
And the answer for how it prints the negative values for i is that, you are using the '%d' that is for signed.
If you want to see the result you can use the '%u' option so it will print the original unsigned value of i.
If you want the result that you want from the program then try to cast the uint to int at the time of condition checking.
精彩评论