Brian
Brian

Reputation: 279

Difference between !(variable) and (!variable)

In either C or C++, is there a conclusive difference between using !(variable) and (!variable) in an if-statement, such as:

if (!(variable)) { .. // do something }

or

if (!variable && !(variable2)) { .. // do something }

such that one version delivers a different result over the other?

Upvotes: 3

Views: 375

Answers (5)

Chris A.
Chris A.

Reputation: 6887

They should never evaluate to different things. Parentheses used this way are really for grouping operations, but in this case, you're not grouping any operations, just the expression itself.

So !(x) is just a pedantic way of writing !x

Now, if you had an operation inside the parentheses, that's where the differences start.

Upvotes: 1

anizzomc
anizzomc

Reputation: 252

There is no difference between

!(variable) 

and

(!variable)

but if you are using operators that has different precedence you will have a difference. For example, if you write

!(varible1 && variable2) 

is not the same as

!varible1 && variable2

because the NOT will be applid to the whole operation in the first case and only to varible1 in the second case.

May be you are getting a problem with the evaluation, C has lazy evaluation, so when the execution detects that boolean evaluation has a result, it doesn't try the other values. So, now consider instead of variables you have functions.

int foo() { printf("foo\n"); return 1; }
int bar() { printf("bar\n"); return 0; }

If you write

if (foo() && bar()) { ... }

you will get

foo
bar

but if you write

if (bar() && foo()) { ... }

you will only get

bar

because the evaluation will be false, doesn't matter the result of foo

Upvotes: 4

cmutt78
cmutt78

Reputation: 859

Its all about order of operation. Using !(variable) will evaluation all conditions inside of the parenthesis then do the ! (or NOT) to determine whether to enter the if statement where-as (!variable will do the NOT specifically on the variable itself.

So in the situations:

!(true && false) = true
!(true && true) = false
(!true && !false) = false
(!true && true) = false
!(true && !false) = false

...and so on

Hope this helped.

Upvotes: 8

Seth Carnegie
Seth Carnegie

Reputation: 75140

No, in your example the first one (although the parens are unbalanced :)) behaves exactly like it would if there were no parentheses, and the second behaves the same way. You can even do this

if ((!((((variable)))))) { ... }

But don't :)

Upvotes: 1

Jordan
Jordan

Reputation: 5058

The only way it would make a difference is if the variable is an expression, then its a matter of operator precedence. Otherwise && has lower precedence than !

Upvotes: 6

Related Questions