Unary plus and minus
What you'll learn: How to use the unary plus and minus operators to indicate or flip the sign of a number.
The "Solo" Operators
Most math operators you have seen so far, like addition (+) or multiplication (*), are binary. This means they need two numbers to work (like 5 + 3). However, "unary" operators are special because they only need one operand. They sit right in front of a single variable or number to tell you something about its state.
Unary Minus (-)
The unary minus is the one you will use most often. It represents negation. Think of it like a "flip" switch for a number’s sign. If you have a positive number, the unary minus makes it negative. If you have a negative number, it cancels out the negative and makes it positive.
Imagine you are playing a game where your score is 10. If you hit a "penalty" zone, the game might calculate your new score as -score. The operator takes your 10 and flips it to -10.
Unary Plus (+)
The unary plus is the quieter sibling. Technically, it exists to represent a positive value, but in C (and most math), numbers are assumed to be positive anyway if there is no sign. Using +5 is exactly the same as using 5.
You won't see it used often in logic, but programmers sometimes use it to align their code visually when they have a list of positive and negative numbers, making the code easier to read at a glance.
Seeing it in C
Here is how these operators look when applied to variables:
#include <stdio.h>
int main() {
int original = 25;
// Unary minus flips the sign
int negative = -original;
// Unary minus flips a negative back to positive
int backToPositive = -negative;
// Unary plus doesn't change anything
int explicitlyPositive = +original;
printf("Original: %d\n", original); // 25
printf("Negative: %d\n", negative); // -25
printf("Back to Positive: %d\n", backToPositive); // 25
return 0;
}
How they behave
These operators have very high "precedence." This means they are usually processed by the computer before the binary math happens. If you write -5 + 10, C first attaches the minus to the 5 to make it "negative five," and then adds 10 to it, resulting in 5.
Key takeaway
Unary minus (-) flips the sign of a value, while unary plus (+) leaves the sign as-is.