0

I have the following lines on my code:

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

   currentSongNumber = currentSongNumber++;

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

But i get the result:

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

So why has it not chaged to three does ++ only work when iterating?

Nicholas Muir
  • 2,897
  • 8
  • 39
  • 89

5 Answers5

4

The post-increment operator returns the old value and then it increments. By assigning back to the same variable, you discard the increment done to the variable.

So when you do

currentSongNumber = currentSongNumber++;

it is equivalent to the following code:

int oldValueOfCurrentSongNumber = currentSongNumber;
currentSongNumber = currentSongNumber + 1;
currentSongNumber = oldValueOfCurrentSongNumber;  // This is because of your assignment
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Try just this code: currentSongNumber++;

1

Because you are using post increment

so either try this

currentSongNumber = ++currentSongNumber;

or this

currentSongNumber++;

or this

++currentSongNumber;
Manish Menaria
  • 23,899
  • 3
  • 21
  • 23
1

You are using post increment. Click here to see the difference between pre-increment and post increment. In your code try pre increment.

++currentSongNumber;

This will give you desired output.

In your code, If you use currentSongNumber = currentSongNumber++; than first the value of currentSongNumber will be assigned to itself, which is same as previous and than the increment will take place.

Or you can just use simply currentSongNumber = currentSongNumber+1;, to avoid confusions.

Community
  • 1
  • 1
Kaushal28
  • 5,377
  • 5
  • 41
  • 72
  • `++` is syntactic sugar which allows to write only `currentSongNumber++`. You should not encourage the OP to write this useless affectation. `++currentSongNumber` or `currentSongNumber++` is enough here. – Arnaud Denoyelle Jun 17 '16 at 09:35
1

Just try this at home:

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

  currentSongNumber++;

   Log.d ("Playlist", "Current Song Number has changed to: "+ currentSongNumber );
Saeed Sharman
  • 765
  • 5
  • 24