What is the difference between post-increment and pre-increment in programming? Provide examples.

Computer Science

ScanSolve AI Answer

Answer

Post-increment (variable++) uses the variable's original value in the expression first, and then increments the variable. Pre-increment (++variable) increments the variable first, and then uses its new value in the expression.

Here are examples:

Post-increment (variable++)

int x = 5;
int y = x++; // y gets the original value of x (5), then x becomes 6

// After this code:
// x is 6
// y is 5

Pre-increment (++variable)

int a = 5;
int b = ++a; // a becomes 6 first, then b gets the new value of a (6)

// After this code:
// a is 6
// b is 6
Was this helpful?

Still stuck on this one?

Ask a follow-up, and the answer starts from this question.

Got a different question?Ask your own question