Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why write `!!x`, when `x` will do? [duplicate]

Tags:

c++

boost

I often see experienced programmers write !!x, even though the expected expression is a Boolean (i.e., zero or not zero) and not an integer.

For example, a line from boost:

BOOST_ASSERT(!!p); // where `p` is a pointer

What's the point of !!p when just p will do?

What I understand by a Boolean parameter is an expression converted to a value of integral type, and the value is compared against zero, explicitly or implicitly (with if or its ternary operator equivalent).

Thus, anything that takes a Boolean and expects only 0 or 1 is wrongly implemented, if my understanding of Boolean is correct.

For clarification: it's obvious that ! converts to bool; the question is explicitly asking for why.

like image 305
Hrisip Avatar asked Dec 06 '20 17:12

Hrisip


People also ask

What will happen if we insert duplicate key in map?

If the key is duplicate then the old key is replaced with the new value.


1 Answers

By default, BOOST_ASSERT(expr) expands to assert(expr). That C++ assert function takes a scalar argument, not bool. Thus, your statement, "the expected expression is a boolean," is not correct.

Classes in C++ can implement operator bool(); the basic_stream classes are examples of such: assert(std::cin) will not work. The !! operator forces the use of std::cin::operator bool(), and bool after !! will be evaluated to int 0 or 1. This is shorter than assert(bool(std::cin)).


If I were a boost author, I would expand BOOST_ASSERT(expr) to assert(!!(expr)) - as is done for ( BOOST_LIKELY(!!(expr)) ? ((void)0) ).

like image 138
273K Avatar answered Sep 24 '22 12:09

273K