bVariable = !!iVariable vs. bVariable = (iVariable != 0)

  • A+

I encountered code like:

bIsOk = !!m_ptr->isOpen(some Parameters) 

The datatype of bIsOk is bool, isOpen(..) returns BOOL (defined as int)

The engineer told me that was said to be the most efficient way to get from BOOL to bool.

Was that correct? Is it still nowadays? 2019?


The reason for the !! is not efficiency - any decent compiler will compile it to the exact same thing as any other non-bonkers way of converting, including just relying on an implicit conversion - but that it suppresses a compiler warning about an implicit narrowing to a bool present in older versions of Microsoft's compiler in VisualStudio (I don't know when it was removed, but I just checked with VS2017 and it no longer seems to give the warning).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: