Xavier Imbs Xavier Imbs - 1 year ago 78
C++ Question

Odd notation for `if` statement

I'm looking through some legacy code where I have encountered the following


if (!(foo == bar)){
// lots of code here

What is the advantage of writing this over

if (foo != bar){

If it's relevant, the code base is C++.

Many thanks.

Answer Source

They ought to be equivalent, for plain old data types they certainly are, but if the author has (unconventionally) provided an overloaded operator for == and not for != then the second way of writing this will not be available to you.

For readability though, I think I would prefer to see

if (foo == bar){
    // do nothing
} else {
    // lots of code here

although the clearest way of all would be to adjust the codebase to provide the != operator, and for you to adopt the second way you have written this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download