Code:
int num = 5;
if (!num == 5)
{
do this
}
else
{
do something else
}
With the NOT operator it would reverse the result and execute that ELSE statement instead. In English it would read, "If num is NOT the same as 5". In that case num IS equal to the number 5 so it would execute the else statement instead.
Since num is the same as 5 the If statement would be TRUE and execute if statement. But that is where the NOT operator kicks in. It will take the TRUE result and turn it to FALSE result. If the result is FALSE the if statement will not execute, instead the ELSE is executed. If you have no ELSE it skips the if statement. I use these all the time in programing to make decisions.
This description is wrong. It doesn't match the code.
The reason is operator precedence, an important concept in any language, but especially important in C (and C-like languages) because of the large number of operators.
In this code:
The ! operator has higher precedence than the == operator, so it's evaluated earlier.
Your description ""If num is NOT the same as 5" makes it seem like this is how it's evaluated:
That is, as "If NOT (num is equal to 5)". But because of precedence, it really evaluates like this:
which is "If (NOT num) is equal to 5". Then you have to ask yourself, "Exactly what does "(NOT num)" evaluate to? The rest of the comparison, "is equal to 5", has 5 as an integer number. So does "(NOT num)" have a numerical value? If so, what is that number?
As it turns out, the ! operator has a very simple numerical result: if its operand is 0, the result is 1; if the operand is non-0, the result is 0. In short, it converts 0 to 1, and any non-0 to 0.
In this case, the operand is the variable num, whose value is 5 (a non-0 value). So the result is 0, and 0 is then compared to 5. The result of that comparison is false.
It happens that this false outcome is the same as:
or:
but it won't always work out that way. With different sub-expressions or different operators, the result may be different. Always use the simplest expression that accomplishes the goal.
I see no reason to use a more complex expression, when the one using != is simpler and has no precedence rules to bungle. It reads "If num not equal to 5", which seems eminently clearer and simpler to me.
Know your operator precedence. If you don't know it,
look it up. Most C books also have a table somewhere in them, which also covers operator associativity (yet another trap for the unwary (or unparenthesized)).