1

I saw the code below recently:

std::error_code ec;

// --- some code

if (!!ec)
{
//error reaction
}

For what purpose the !! is used? The only idea is to force bool operator, but for what? May it have sense for some implementations of boost error types?

brandy
  • 31
  • 5

2 Answers2

1

The use of !! inside if statement is redundant, as inside an if a value may be contextually converted to bool even if the casting is marked as explicit.

However, in an assignment this trick may be a substitute for an explicit cast:

std::error_code ec;

// some code

// bool is_error = ec;   // compilation error, operator bool is explicit
bool is_error1 = !!ec;   // ok
bool is_error2 = (bool)ec; // better, one may argue
bool is_error3 = static_cast<bool>(ec); // to avoid C-style cast
bool is_error4 = ec.value() != 0; // most verbose, also possible

It might be that the if(!!ec) is a copy-paste from an assignment expression.

See also: When can I use explicit operator bool without a cast?


A side note: there might be of course a case where this trick is relevant inside if - in case a type implements operator! and lacks operator bool - but this is not the case with std::error_code.

Amir Kirsh
  • 12,564
  • 41
  • 74
0

It is a double negative. example:

int main()
{
    bool varTrue = true;
    std::cout << "varTrue = " << varTrue << std::endl;
    std::cout << "!varTrue = " << !varTrue << std::endl;
    std::cout << "!!varTrue = " << !!varTrue << std::endl;

}

Output

varTrue = 1
!varTrue = 0
!!varTrue = 1

It seems useless

  • Its about `std::error_code`... Possibly it may be used like this : `auto b = !!ec;`... – brandy Sep 08 '20 at 18:18
  • 1
    nobody said `varTrue` was a `bool`. In fact, it is a `std::error_code` in the question. – Wyck Sep 08 '20 at 18:23