+ 1
In a loop Prefix and Postfix increment are the same?
Prefix Example 1.1 X= 5; y = ++x; // x is 6, y is 6 Postfix Example 1.2 x = 5; y = x++; // x is 6, y is 5 Loop example int num = 1; while(num < 6) { cout << "Number : " << num << endl; num++; <-------*postfix increment confusion * } Why output is 1,2,3,4,5 Instead of 1,1,1,1,1
1 ответ
+ 1
In the loop example, you are not assigning the result of the postfix increment to another variable, as done in the other ones.
You see, prefix and postfix increments, when used alone, yield equivalent results, because in either case, you are incrementing the variable. That is why you end up with increasing numbers.
The difference between both operators relies on its use in conjunction with other operators, such as assigment, or when inside of bigger expressions.
Remember than prefix increment performs the increment to the variable *before* its result is available to other operations.
On the other hand, postfix increments are executed *after* the value the variable had prior to that is used in the bigger expression.
Here is an example code using the prefix increment inside a comparison.
https://code.sololearn.com/c2277HtQvo6a/?ref=app