Xavier Imbs Xavier Imbs - 2 months ago 10
C++ Question

Odd notation for `if` statement

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

if
statement

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

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.