简体   繁体   English

在 c 中省略 for 循环的最后一部分

[英]omitting last part of a for loop in c

Are these two peaces of code equivalent ?这两个代码等效吗?

for(int i=0; i<10; i++){
        //some thing
}

and

for(int i=0; ++i<10; ){
        //some thing
}

if they are the same which one is more standard to use?如果它们相同,使用哪个更标准?

I wouldn't write it as for(int i = 0; ++i < 10; ) , and ++i differs from i++ due to the order of operations.我不会把它写成for(int i = 0; ++i < 10; ) ,并且++ii++由于操作顺序不同。 ++i increments i then "returns" it, i++ "returns" i then increments it. ++i递增i然后“返回”它, i++ “返回” i然后递增它。

No, these are not the same thing.不,这些不是一回事。 You must be aware of the working of prefix increment and postfix increment.您必须了解前缀增量和后缀增量的工作原理。

In the second case, in the first iteration of the for loop, variable 'i' will have value 1, but, in the first case the variable 'i' will have value 0 and so on.在第二种情况下,在 for 循环的第一次迭代中,变量“i”的值为 1,但在第一种情况下,变量“i”的值为 0,依此类推。

Therefore the second loop will run 9 times only whereas the first loop will run 10 times因此,第二个循环将只运行 9 次,而第一个循环将运行 10 次

No its not the same thing but if you write it this way :不,它不是一回事,但如果你这样写:

for(int i=0; i<10; ){ //some_thing i++; }

its the same一样的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM