the !operator

i dont have trouble understanding the && operator or the || operator but when it comes to the !operator i dont understand it for some reason. here is an example. this code confuses me only because theres an ! outside the expression..

1
2
3
4
5
6
7
8
9
   if (!(income >= MIN_INCOME || years > MIN_YEARS))
 {
 cout << "You must earn at least $"
 << MIN_INCOME << " or have been "
 << "employed more than " << MIN_YEARS
 << " years.\n";
 }
 else
 cout << "You qualify.\n";
1
2
3
4
5
6
7
8
if (true)
 cout << "This is true" << endl;
if (!true)
 cout << "This is not true" << endl; // won't run
if (false)
 cout << "This is false" << endl; // won't run
if (!false)
 cout << "This is not false" << endl;
Without the ! operator, I'm sure you understand that it means if either one of those expressions is true the body will run.

The ! operator changes that so that the if body will run if either of those expressions is false.

In other words, if income >= MIN_INCOME or years > MIN_YEARS is NOT true, run body.
so in this case if either one of those expressions in the code were to be false it wont run at all right? but with the help of the ! operator it just takes one of the two to be true and it will run the whole block of code?
No, no. With the OR operator, if either the left or right are true, it returns true. The not operator (!) makes it so that whatever the value being returned is inverted. True becomes false, false becomes true. Here, it requires both values to be false for the if statement to return true, and run the block of code. If either are true, the or operator returns true, the not operator makes it false, and the block of code is not run.
Let's break your condition into smaller parts, remembering that all operator! does is flip the Boolean value.

if(!(income >= MIN_INCOME || years > MIN_YEARS))
->if()
-->!()
--->income >= MIN_INCOME || years > MIN_YEARS
(For the sake of brevity, I'll call the above a Boolean variable condition)

Case 1 (condition = true):
-->!(condition) --> !(true) --> false
->if(!(condition)) -> if(!(true)) -> if(false) -> not executed

Case 2 (condition = false):
-->!(condition) --> !(false) --> true
->if(!(condition)) -> if(!(false)) -> if(true) -> executed

Simple as that.
ahhhh i see... it took me a while but i think i get the concept now. i took a second look at the code i posted and i notice in the else block of code it outputs "you qualify" generally, else, is used as a alternative if the condition in the IF were to be false...but having the ! operator it makes the condition in the IF statement false if anything inside were to be true...that is why the else block of code is executed..im confusing myself a little but i think i understand it. thank you all for commenting and trying to help me out i appreciate it
Last edited on
Topic archived. No new replies allowed.