1

following code giving this error :

int main()
{
    int i = 4, j=10;
    int k, l;

    k = ++ (++ i);
    l = (j++) ++;

    cout << "k : " << k << endl;
    cout << "l : " << l << endl;

    return 0;
}

It will be very helpful, if anyone could explain why that error occurs.

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
taj
  • 255
  • 1
  • 5
  • 9
  • I see college season has started again. Both lines are **undefined behavior**. But since you would never write code like this in real life why why why ask about. Don't write code like this. – Martin York Sep 28 '13 at 16:30
  • @Loki One is just ill-formed. The other always used to be undefined behaviour, but I'm not certain it is now; the rules changed in C++11. I agree though that one should never do this. – Alan Stokes Sep 28 '13 at 16:34

3 Answers3

5

The result of j++ is the old value of j rather than a reference to j. You can't apply another increment to it because you can't increment values.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
  • 1
    (Whereas `++i` increments `i` and returns a reference to the variable itself so you can increment it again. But using multiple increment operators on the same thing can cause problems; it's really best not to.) – Alan Stokes Sep 28 '13 at 15:42
  • 1
    And this only holds for scalar types. If you write your own class and overload `operator++(int)`, `(j++)++;` can be legal. – jrok Sep 28 '13 at 16:05
2

Because when you write X ++, X must be a variable, X must be the thing you are incrementing. So (j++) ++ is an error because (j++) is not a variable. Just write j += 2 instead.

Note to experienced programmers, I know this is a gross simplifcation.

john
  • 85,011
  • 4
  • 57
  • 81
  • Your post indirectly says `(++ i)` is a variable – P0W Sep 28 '13 at 15:39
  • @P0W How so? I only mentioned j++ not ++i. – john Sep 28 '13 at 16:00
  • @john Because `(++i)++` is not an error, and the only way you suggest this can be possible is if `++i` is a variable. – Gavin Smith Sep 28 '13 at 18:09
  • 1
    @GavinSmith Right, that's the gross simplification. I thought this was the simplest way to present what is quite an advanced topic, the details of which I doubt the OP is concerned about. – john Sep 28 '13 at 19:34
2

Just write j += 2. Why you're using the operator++ in a wrong way ? Apply KISS.

andre_lamothe
  • 2,171
  • 2
  • 41
  • 74