[英]Setting an integer value before loop
I have a loop like so 我有一个像这样的循环
int current = -1;
for (int i=0; i < size; i++) {
... some stuff
if (i > current || current == -1) {
current = i;
}
}
So basically, I don't have an original value for current before the loop. 因此,基本上,循环之前我没有电流的原始值。 Is this a good way to ensure current value is set to the first instance of i or could it be written better?
这是确保将当前值设置为i的第一个实例的好方法,还是可以更好地将其写入?
Thanks. 谢谢。
This one works nicely if current
will only be used inside the loop: 如果仅在循环内部使用
current
则此方法效果很好:
for (int i = 0, current = i; i < size; i++) {
// etc..
}
That's the usual way people do it, yes. 这是人们通常的做法,是的。
There's no need for current == -1
though, since i > current
will evaluate to true
the first iteration, and current
is set to i
after that. 不过,不需要
current == -1
,因为i > current
在第一次迭代时将评估为true
,然后将current
设置为i
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.