0

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
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

3 Answers3

2

5++ is just incorrect.

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

nullptr
  • 11,008
  • 1
  • 23
  • 18
1

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

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;
}
kfsone
  • 23,617
  • 2
  • 42
  • 74
  • Just an obligatory warning to those who might get the idea, `int` is definitely not a class. – chris Dec 15 '13 at 01:03