-1

Came across using !! in C++ during condition check

if ( !! (flag != 0 )){..
}

This could be directly used like

if( flag != 0 ){..
}  

Is there any specific corner use case in C/C++ or is it just a form of coding style ?

Nerdy
  • 1,016
  • 2
  • 11
  • 27
  • 4
    c and c++ are 2 very different languages, and often have very different answers. Please tag only one language. – cigien Aug 26 '20 at 07:07
  • It's a dumber way of writing `(bool)flag` - which is also compatible code between C and C++, unlike `!!`. – Lundin Aug 26 '20 at 10:02

1 Answers1

3

In this case, it's superfluous, but in general this style is used to convert the actual expression value to

  • an integer type in C.
  • a boolean type in C++.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Didn't you mean "to bool"? – r3mus n0x Aug 26 '20 at 07:04
  • @r3musn0x It's `int` in C. – Sourav Ghosh Aug 26 '20 at 07:04
  • 1
    ...unless it is C++ and operator `!` is overloaded... – Alex Lop. Aug 26 '20 at 07:04
  • 1
    More specifically, in C be it'd be used to convert a value to either 0 or 1. But regardless, in this case it's pointless since `!=` already guarantees to evaluate to either 0 or 1. However, some people do it anyway because there's a common misconception that just because any non-zero value is truthy that boolean operators are allowed to produce any non-zero value as well. – jamesdlin Aug 26 '20 at 07:30