我的代码中包含以下几行:

   Log.d ("Playlist", "Current Song Number is: "+ currentSongNumber );

   currentSongNumber = currentSongNumber++;

   Log.d ("Playlist", "Current Song Number has changed to: "+ currentSongNumber );


但我得到结果:

Current Song Number is: 2
Current Song Number has changed to: 2


那么为什么在迭代时++只起作用呢?

最佳答案

后递增运算符返回旧值,然后递增。通过分配回相同的变量,可以放弃对变量所做的增量。

所以当你这样做

currentSongNumber = currentSongNumber++;


它等效于以下代码:

int oldValueOfCurrentSongNumber = currentSongNumber;
currentSongNumber = currentSongNumber + 1;
currentSongNumber = oldValueOfCurrentSongNumber;  // This is because of your assignment

10-05 20:01