0

I know that --> is not an operator. It is in fact two separate operators -- and >.And it is same as like below opearation.

while( (x--) > 0 )

Now i ran two programs but it arose some confusion in me.

First Program:

int main(void)
{
    int x = 10;
    while(----x>0)
   {
     cout<<x<<endl;
   }
}

Output: 8 6 4 2

Second Program:

int main(void)
{
    int x = 10;
    while(x---->0)
   {
     cout<<x<<endl;
   }
}

I got compilation error:

lvalue required as decrement operand

Actually what is happening here?? why the first program is running successfully but not the second one??

Barmar
  • 741,623
  • 53
  • 500
  • 612
Setu Kumar Basak
  • 11,460
  • 9
  • 53
  • 85

1 Answers1

15

Result of --x is an lvalue, you can apply -- to it again: --(--x).

Result of x-- is an rvalue, since -- needs an lvalue, you can't do (x--)--.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 10
    And result of routinely writing code that looks like `----x>0` is looking for a new job ;) – mah Jan 21 '16 at 17:54
  • Just a question, as its --x this reduces 1 from x right? Im not that good with C++ and found this question interesting. – S A Jan 21 '16 at 18:08
  • Is there some exception to the rule about changing a value twice without a sequence point that stops `----x` from being undefined behavior? Unlike most such situations, there is zero ambiguity about the sequence of operations. But I don't recall the wording of the rule caring about the ambiguity. I thought it just said doing this was undefined behavior. – JSF Jan 21 '16 at 18:43
  • @JSF: Since C++11, there are no sequence points, there are only ordered ("sequenced before") and unsequenced computations (and indeterminately sequenced, which is not an issue in this case). I'll dig a bit deeper but I think one effect of the change was to make `--(--x)` not only syntactically and semantically correct, but also well-defined. – Ben Voigt Jan 21 '16 at 22:14
  • @JSF: The side-effect of `--x` (as `x-=1`) is sequenced before its value computation. Since the value computation of `--` operand is sequenced before the value computation of the operator result itself, it means that in `--(--x)`, the side effect of `(--x)` happens first, then value computation of `(--x)`, then value computation of `--(--x)`. Unfortunately I don't see a restriction on the sequence of the side effect of `--(--x)`. – Ben Voigt Jan 21 '16 at 22:25
  • why they have closed my question and marked as duplicate?? The question is not same as my question :(. – Setu Kumar Basak Jan 22 '16 at 05:50
  • @setubasak: Yes it is. Read the answers to the other one more closely. – Ben Voigt Jan 22 '16 at 15:43