-1

I don't consider myself to be bad at programming, but there's been something troubling me since the past few days.

int counter = 3;
++counter;

Is the following code above the same as counter++;.

Asker123
  • 350
  • 1
  • 3
  • 15

1 Answers1

6

It is similar, but not the same.

In your expression it doesn't matter, but if you had something more complicated, like System.out.println(counter++), it would make a big difference.

For example: int counter = 3; System.out.println(counter++)

This will print 3, then increment counter to 4.

However, if you do

int counter = 3; System.out.println(++counter)

it will print 4 because it increments prior to giving the value as a parameter to the print function.

It's a question of when the increment is performed, the prefix performs it before other operations, postfix performs it after. They have different precedences.

Chris Chambers
  • 1,367
  • 21
  • 39