如果在一个循环条件下使用会strlen的计算多次吗? [英] Will strlen be calculated multiple times if used in a loop condition?

查看:126
本文介绍了如果在一个循环条件下使用会strlen的计算多次吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如果下面的code会导致多余的计算,或者是编译器特定的?

I'm not sure if the following code can cause redundant calculations, or is it compiler-specific?

for (int i = 0; i < strlen(ss); ++i)
{
    // blabla
}

威尔的strlen()在每次计算时, I 增加?

推荐答案

的strlen()将在每个迭代计算。这是可能的,在理想的情况下,优化器也许能推断出值不会改变,但我个人并不依赖于这一点。

Yes, strlen() will be evaluated on each iteration. It's possible that, under ideal circumstances, the optimiser might be able to deduce that the value won't change, but I personally wouldn't rely on that.

我会做这样的事情。

for (int i = 0, n = strlen(ss); i < n; ++i)

或可能

for (int i = 0; ss[i]; ++i)

只要串是不会在迭代期间改变长度。如果可能,那么你需要或者呼叫的strlen()每一次,或处理它通过更复杂的逻辑。

as long as the string isn't going to change length during the iteration. If it might, then you'll need to either call strlen() each time, or handle it through more complicated logic.

这篇关于如果在一个循环条件下使用会strlen的计算多次吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆