What if (!variable) statement means?

May 9, 2018 at 6:40am
Write your question here.

May 9, 2018 at 8:13am
If n is an integer then:
if ( n )
means "if n is non-zero"

if ( !n )
means "if n is zero"

When necessary, 0 translates to false, anything non-zero to true.

The construct can also be used for testing the condition of iostreams etc. as well.


Is that what you are asking? Your question (as imbedded in the title of your thread and not in the body of your post) is not clear. Maybe you should post the code leading to your question.
Last edited on May 9, 2018 at 8:15am
May 9, 2018 at 8:14am
You can think
if ( ! foo ) ...
as
1
2
const bool bar = foo;
if ( ! bar ) ...

or more verbose:
1
2
const bool bar = foo;
if ( not bar ) ...


You have a variable ("foo" in the example).
The foo has value.

There is some method for converting the value into a bool value.
For example, integer value 0 converts to false (and non-zero values to true).

The operator! negates.


Note that a class type variable might have its own operator!
For example: http://www.cplusplus.com/reference/ios/ios/operator_not/
if ( ! cout ) ...
is thus like
1
2
const bool bar = cout.operator!();
if ( bar ) ...

May 9, 2018 at 1:36pm
works fine on floating point types and pointers (which are integers really) as well. So youll see it on pointers as a null-check.


May 9, 2018 at 2:43pm
The if statement only executes if it evaluates to true, but what if you want an if statement to execute if something is not true...

You can do this..

bool myBool = true;

if (myBool == false) {
//do something here.
}

or you could use the negate operator which switches a value to its opposite.

if (!myBool) {
//this would only execute if myBool is equal to false.
}
Topic archived. No new replies allowed.