Negative Operator -

This page was translated by a robot.

The negative operator is used to explicitly negate an element and is also called unary minus in C. It is always written BEFORE the element to be marked, for example -valueor -1000.






1000
-1000
-1000
1000
#include <stdio.h>

int main(){
  int pos =   1000;
  int neg = - 1000;
  printf("%d\n",     pos);
  printf("%d\n",   - pos);
  printf("%d\n",     neg);
  printf("%d\n",   - neg);
  return 0;
}

Details

The negative operator expects an operand as rvalue and is processed from right to left . The return value is an rvalue and has the same type as the operand.

The semantic meaning of negation is multiplication by -1. The computer performs this negation by forming the respective complement used in the compiler.

In particular, the negative operator is used to mark a fixed integer value written in program code as negative. In this case, the compiler will often not negate the number at runtime, but save the fixed value during compilation in the complement that is finally used.

The following constructs only make sense to a limited extent, but are possible:

1000
-1000
-1000
printf("%d\n", - - pos);
printf("%d\n", - - neg);
printf("%d\n", - - - - - - - pos);

Caution: The following line looks almost the same, but due to the lack of space between the two -, it is the decrement operator that changes the variable:

999
printf("%d\n",  -- pos);

However, this difference is obsolete if the negative operator occurs mixed with the positive operator , since such an operator does not exist and is therefore resolved as separate positive and negative operators:

-1000
-1000
-1000
-1000
printf("%d\n", - + pos);
printf("%d\n",  -+ pos);
printf("%d\n", + - pos);
printf("%d\n",  +- pos);