Using for loop to reverse Iterate over elements of a container/string without warnings in both 32-bit and 64-bit
I just want to reverse-iterate over a container or over a string.
This sample code
for (int i = strlen (str) - 1; i >= 0; i--)
{
...
}
will raise a warning on 64-bit compilation:
warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data
On the other hand,
for (size_t i = strlen (str) - 1; i >= 0; i--)
{
...
}
will cause an infinite loop, since size_t is unsigned.
I know I ca开发者_如何学Pythonn use other techniques, but I just want to use a simple for loop !
How can I write a clean code for both 32-bit and 64-bit compilations?
change to:
for (size_t i = strlen (str); i--; )
{
...
}
精彩评论