Menu
CoddyTech

Post Increment/Decrement

Part of the Fundamentals section of Coddy's C# journey. Lesson 18 of 70.

Increment (++) and Decrement (--) operators can be used in two ways:

Pre-increment/decrement (++x or --x):

  1. The operator goes BEFORE the variable
  2. The value changes IMMEDIATELY
  3. The new value is used in the expression

int x = 5;
int y = ++x;
// x is increased to 6 first, then y becomes 6

Post-increment/decrement (x++ or x--):

  1. The operator goes AFTER the variable
  2. The original value is used first
  3. The variable still changes IMMEDIATELY, so a later use of it in the same expression sees the new value

int x = 5;
int y = x++;
// x increases to 6, and y gets the original value 5

Another example

post-increment:

int score = 5;
int res1 = score++;
// res1 is 5
// score is 6

pre-increment:

int score = 5;
int res2 = ++score;
// res2 is 6
// score is 6

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online C# compiler