开发者

Is there a way to pre increment by more than 1 in Java?

开发者 https://www.devze.com 2023-03-22 15:53 出处:网络
In Java you can do a post increment of an integer i by more that one in this manner: j + i += 2. I would like to do the same thing with a pre increment开发者_运维知识库.

In Java you can do a post increment of an integer i by more that one in this manner:

j + i += 2.

I would like to do the same thing with a pre increment开发者_运维知识库.

e.g j + (2 += i) //This will not work


Just put the increment statement in parentheses. For example, the following will output pre: 2:

int i = 0;
System.out.println(
    ((i+=2) == 0)
    ? "post: " + i : "pre: " + i);

However, writing code like this borders on obfuscation. Splitting up the statement into multiple lines will significantly improve readability.


Not sure if there is a confusion in terminology going on, but += is not a post or pre-increment operator! Java follows the C/C++ definition of post-increment/pre-increment and they are well defined in the standard as unary operators. += is a shortcut for a binary operator. It evaluates to this:

lvalue1 += 5 ;
// is really (almost)
lvalue1 = lvalue1 + 5;

The assembler for the instruction doesn't look exactly like the binary version but at the level your using Java you do not see that.

The post-increment/pre-increment are unary operators that function kind of like this:

i++ ; // is something like _temp = i; i = i + 1; return temp;
++i;  // is something like i = i + 1; return i;

This is just an example of how it works, the byte code doesn't translate too multiple statements for the post-increment case.

In your example, you could say a post-increment occurs but really, its just an increment. which is why I believe you have made the (incorrect) leap that it might be possible to have a pre-increment version of the same operation. But such a thing does not exist in C, C++, or Java.


Something like:

int increment = 42;
int oldI = i;
i += increment;
result = myMethod(oldI);
// Rest of code follows.

But why would you want to do this?


The += is pre increment. If you want post increment simply create wrapper with postInc method which will do this. If you really need this it would be more readable than parenthesis.

0

精彩评论

暂无评论...
验证码 换一张
取 消