08 Feb 2024
Beginner
In programming languages like C, C++, Java, and others, i++ and ++i are both increment operators, but they have a subtle difference in behavior.
-
i++: This is known as the post-increment operator. It increments the value ofibut returns the original value ofibefore the increment.Example:
int i = 5; int j = i++; // j will be 5, i will be 6 -
++i: This is known as the pre-increment operator. It increments the value ofiand returns the updated value ofiafter the increment.Example:
int i = 5; int j = ++i; // j will be 6, i will be 6
In both cases, i is incremented by 1, but the difference lies in the value that is returned or assigned. With i++, the value before the increment is returned/assigned, whereas with ++i, the value after the increment is returned/assigned.