Pre increment and post increment
Solution 1
result = y++ + z-- + x++;
3 1 2 = 6
if you perform this again
result1 = y++ + z-- + x++;
4 0 3 = 7
reason
operator++
returns the original value, before incrementing the variable.
and
++operator
returns the incremented value
--
is same as above just its decrement
Solution 2
Because the postfix operator++
returns the original value, before incrementing the variable. The prefix operator++
increments the varialbe and returns a reference to it. The behaviour can be easily illustrated with an example:
#include <iostream>
int main()
{
int n = 1;
std::cout << n++ << "\n"; // prints 1
std::cout << n << "\n"; // prints 2
int m = 10;
std::cout << "\n";
std::cout << ++m << "\n"; // prints 11
std::cout << m << "\n"; // prints 11
}
Solution 3
when you write x++
it uses the current value of x
and then increases it by one.
you want to write ++x
instead if you want to increase first.
Solution 4
Pre-increment operator(++p)
first increase the value and assign it and post increment operator(p++)
first assign the value and then perform increment operation.Here all variable are post increment i.e it initially assign its value (on buffer) then increase (for y and x by 1) and decrease z by 1. i.e
initially assign 3 + 1 + 2 in buffer(addition is performed on buffer value) and then perform increment/decrements as x= 3,y=4 and z=0
for more information you can read answer on What is the correct answer for cout << c++ << c;? and Why are these constructs (using ++) undefined behavior? questions
Solution 5
The position of ++
matter.
If
++
precedes the variable, e.g.++counter
, the value returned is the value in counter after it has been incremented. If++
follows the variable, e.g.counter++
, the value returned is the value in counter before it has been incremented.
Hoon
Updated on June 14, 2022Comments
-
Hoon almost 2 years
I'm having trouble understanding how Post Increment (
++
), Pre Increment (--
) and addition/subtraction work together in an example.x++
means add 1 to the variable.x--
means subtract 1 from the variable.But I am confused with this example:
int x = 2, y = 3, z = 1;` y++ + z-- + x++;
I assume this means
3(+1) + 1(-1) + 2(+1)
Which means the result should be 7.But when I compile it, I get
6
. I don't understand.int main() { int x=2, y=3, z=1; int result; result = y++ + z-- + x++; //this returns 6 cout << result << endl; return 0; }
-
Siddharth-Verma over 11 yearsIt will first use the value and then* increment
-
jrok over 11 yearsThe code in OP is well defined and can be explained. The links don't answer the question.
-
Toby Speight about 7 yearsWhat language is that? It certainly doesn't look like any C++ I've seen...