-
Notifications
You must be signed in to change notification settings - Fork 0
Coding Tricks
vhirtham edited this page Jun 7, 2019
·
1 revision
Problem:
We want to create a loop that counts down until 0, but this code
for (U32 i=10; i>=0; --i)
...causes undefined behavior, since the loop variable i can never be smaller than zero. If it reaches 0, it will be set to the largest possible value and the loop continues forever. One solution might be to use signed integers, a while loop or a break condition.
Or this little gem:
for (size_t i = 11; i-- > 0; )
...This swappes the order of the comparison and the decrement. Source: https://softwareengineering.stackexchange.com/questions/225949/using-unsigned-integers-in-c-and-c