简体   繁体   English

如何在不使用++I的情况下进行预增量?

[英]How to do pre increment without using ++I?

I don't think that the following:我不认为以下内容:

i += 1

or或者

i = i + 1

is the same as ++i.与 ++i 相同。 Or am I wrong?还是我错了? Is there any way to do pre increment without using ++ operator?有没有办法在不使用 ++ 运算符的情况下进行预增量?

They are the same.他们是一样的。 Unless for very simple expressions (like a loop condition), it is better to avoid the ++ or -- operators.除非对于非常简单的表达式(如循环条件),否则最好避免使用++--运算符。

I can't add comments so posting related stackoverflow question here:我无法添加评论,因此在此处发布相关的计算器溢出问题:

How do the post increment (i++) and pre increment (++i) operators work in Java? Java 中的后增量 (i++) 和前增量 (++i) 运算符如何工作?

As Jeremy already commented, i+=1;正如杰里米已经评论过的那样, i+=1; and i=i+1;并且 i=i+1; are equivalent to ++i or i++ if they standalone lines of code.如果它们是独立的代码行,则等效于 ++i 或 i++。 To achieve pre/post increment you will have to do the increment before/after the line where you want to use the variable as per the case.要实现前/后增量,您必须根据情况在要使用变量的行之前/之后进行增量。

eg- for post increment of a variable named i:例如-对于名为 i 的变量的后增量:

//use value of i here
i += 1;

for pre increment:对于预增量:

i += 1;
//use value of i here

In case of a loop, post increment is pretty straight forward:在循环的情况下,后增量非常简单:

for(var i=someValue; i<maxValue; i+=1){
//code here
}

For pre increment:对于预增量:

var i = someValue + 1;
for(; i<maxValue; i+=1){
//code here
}

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

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