2

Confusion with ++ and -- operator

int a = 10;
printf("%d\n", -(--a) ); // valid

output: -9 

But, problem occurs when following is used:

printf("%d\n", --(-a));  // error, invalid

Why?

Shahriar
  • 13,460
  • 8
  • 78
  • 95
  • 5
    You seem to be interpreting -(--a) as a sequence of letters with some magical properties. Look at both, write down what exactly each expression is supposed to do, and it should be obvious why one is allowed and the other not. Just replace "--" with "pre-decrement operator" and "-" with "unary minus". – gnasher729 Dec 31 '14 at 16:43

1 Answers1

10

The ++ and -- operator works on only lvalue, not value. An lvalue is something that can stand on the left side of an assignment.

printf("%d\n", -(--a) );

Here, -- operator works on variable a, so this is valid.

But,

printf("%d\n", --(-a));

Here, (-a) returns a value. -- is applied to a value, which is not valid. This is because -- modifies a variable, and int value can't be modified (For example you can't do 7 = 5 but you can do a = 5)

Shahriar
  • 13,460
  • 8
  • 78
  • 95
  • 4
    Not only on variable, but on what is called 'lvalue' (named after being allowed on left side of assignment. For example `--*expr` or `--expr1[expr2]`, `--expr->field` are allowed. – zch Dec 31 '14 at 16:43