I am confused about how Unary Operators work in C for Ones Complement, Logical Negation and preincrementing.
Ones complement works against 0 like this:
int main()
{
int a;
a = ~0; // Ones complement
printf("%d",a); // prints as -1.
}
And logical negation works against 0 like this:
int main()
{
int a;
a = !0; // Logical negation
printf("%d",a); // prints as 1.
}
But Preincrement against 0 generates a compiler error:
int main()
{
int a;
a = ++0; //pre incrementing 0. error: non-lvalue in increment
printf("%d",a);
}
Why don’t all three work considering they are all Unary Operators?
The increment (
++) and decrement (--) operators modify the thing that follows them. You can’t modify a literal or a constant. In contrast, the!and~operators merely operate on a value, they don’t then assign the result anywhere.Loosely speaking,
++nmeansn = n + 1; n. That is, “take the value ofn, add one to it, write that value back ton, and return the new value as the value of the expression.” So++0would mean0 = 0 + 1; 0: “take the value of0, add one to it, write that back to0, and return the new value as the result of the expression.” Literals and constants cannot be left-hand values (you can’t assign to them).In contrast,
~nmeans “take the value ofnand apply a bitwise NOT operation to it, return the result as the result of the expression”.nis unchanged,~doesn’t write back the updated value to its operand.So for example:
vs.
Increment (
++) and decrement (--) are just different in that way than for!or~(or, I think, any other unary operator — at least, I can’t immediately think of any others that modify their operand).