Preincrement and Postincrement

201 views Asked by At

I've been trying to understand how post and pre increments work lately and I've been over thinking it too much.

Does "Product" become 25 after one iteration?

Product *=5++

And does "Quotient" become 5/6 after one iteration?

Quotient /= ++x
3

There are 3 answers

0
nullptr On

5++ is just incorrect.

Quotient /= ++x; is the same as x = x + 1; Quotient = Quotient / x; (assuming these are just plain numbers).

0
Kerrek SB On

Your code isn't valid C++, since the built-in post-increment operator may only be applied to lvalues, but literal integers are rvalues.

Beside that, the value of a (built-in) pre-increment expression is the incremented value, while the value of a post-increment expression is the original value.

1
kfsone On

Pre-increment modifies the variable and evaluates to the modified value.

Post-increment evaluates to the value of the variable and then increments the variable.

int a = 5;
int b = ++a; // a = a + 1; b = a
int c = a++; // c = a; a = a + 1

Consider these simple implementations of ++ for int

int& int::preincrement()
{
    this->m_value += 1;
    return *this;
}

int int::postincrement()
{
    int before = this->m_value;
    this->m_value += 1;
    return before;
}