开发者

"value++" in java [duplicate]

This question alrea开发者_如何学Gody has answers here: Closed 11 years ago.

Possible Duplicate:

java operator ++ problem

public class A {

public static void main(String[] args) {

    int nir = 5;
    nir = nir++;

    System.out.print(nir);
    }
}

Why is the output 5 and not 6?

Please don't tell me what to do in order to get 6.. obviously I am able to get to 6, it's just that the syntax looks fine to me and an explanation about what wrong with that will do better, thanks.


Because the expression nir++ evaluates to the old value of nir. So exp(nir++) is equivalent to:

int oldValue = nir;
nir = nir + 1;
exp(oldValue);

In your case that means:

int oldValue = nir;
nir = nir + 1;
nir = oldValue;

Which of course makes no sense because it basically does nothing.


nir++ returns nir value and increases it after that. So nir++ when nir is equal 5 returns 5 and sets nir to 6. After that you set nir to 5, so it returns 5. Just skip nir= or use ++nir.


Because nir++ gets the value of nir before incrementing it, if you want the value to be 6 use ++nir, which states increment nir before giving the value.


Try nir = ++nir; It will be different. It will firstly +1 then set the value to nir.


You don't have to reassign the variable using ++ incrementation.

nir++ is post incrementation : first the variable is used into the expression and then it is incremented. So here you assign the value 5 to nir.

If you want the value to be incremented and then used you can use pre incrementation ++nir.


This is what happens:

int nir = 5;

nir is set to 5


nir = nir++;

The right hand side is replaced by the current value of nir, and then nir++ is evaluated. In other words:

nir = nir++;
//simplifies to (not executed!)
nir = nir;
//simplifies to (not executed!)
nir = 5;

Nextnir++ is executed. nir is now 6

Next nir = 5;is executed. nir is now 5


I was a little surprised to see that no one had (in addition to explaining the problem) suggested a different operator that's a lot less obscure, at least for me - even though I've been doing C and/or Java for 30+ years:

nir += 1;

The nice thing about this is that it looks a lot more like the assignment that it (or ++nir) is.


Your line:

nir = nir++;

Means "assign the value of nir (5) to variable nir and then increment the value by 1. This increment operation is lost in the process. Since nir gets overwritten.

You want:

nir++;

or

nir = ++nir;

If you instead had

int a = 5;
int b = a++;

a would get set to 6 and b would be 5.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜