开发者

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--; )
{
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜