Aaron Nguyen
Aaron Nguyen

Reputation: 1

Preincrement and Postincrement

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

Upvotes: 0

Views: 190

Answers (3)

kfsone
kfsone

Reputation: 24249

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;
}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476940

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.

Upvotes: 1

nullptr
nullptr

Reputation: 11058

5++ is just incorrect.

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

Upvotes: 2

Related Questions