for循环的限制是一次计算还是与每个循环一起计算? [英] Are the limits of for loops calculated once or with each loop?

查看:49
本文介绍了for循环的限制是一次计算还是与每个循环一起计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是在下一次循环(12332 * 324234)中计算一次还是每次循环计算极限?

Is the limit in the following loop (12332*324234) calculated once or every time the loop runs?

for(int i=0; i<12332*324234;i++)
{
    //Do something!
}

推荐答案

为此,它计算了一次,或者更有可能是0次.

For this it it calculated once, or more likely 0 times.

编译器会为您优化乘法.

The compiler will optimize the multiplication away for you.

但是,如果您有类似的情况,情况并非总是如此.

However this is not always the case if you have something like.

for(int i=0; i<someFunction();i++)
{
    //Do something!
}

因为编译器并不总是能够看到someFunction将返回什么.因此,即使someFunction每次确实返回一个常量值,如果编译器不知道,它也无法对其进行优化.

Because the compiler is not always able to see what someFunction will return. So even if someFunction does return a constant value every time, if the compiler doesn't know that, it cannot optimize it.

编辑:正如MainMa在评论中所说,在这种情况下,您可以通过执行以下操作来消除成本:

EDIT: As MainMa said in a comment, you are in this situation you can eliminate the cost by doing something like this:

int limit = someFunction();
for(int i=0; i<limit ;i++)
{
    //Do something!
}

IF ,您可以确定someFunction()的值在循环期间不会改变.

IF you are certain that the value of someFunction() will not change during the loop.

这篇关于for循环的限制是一次计算还是与每个循环一起计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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