Is !! a safe way to convert to bool in C++?
Asked Answered
A

18

55

[This question is related to but not the same as this one.]

If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (?:) to convert to a bool. Using two not operators (!!) seems to do the same thing.

Here's what I mean:

typedef long T;       // similar warning with void * or double
T t = 0;
bool b = t;           // performance warning: forcing 'long' value to 'bool'
b = t ? true : false; // ok
b = !!t;              // any different?

So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (e.g., with void * or double for T)?

I'm not asking if !!t is good style. I am asking if it is semantically different than t ? true : false.

Anarthrous answered 15/10, 2008 at 19:35 Comment(6)
When I see a line like "b = t ? true : false;" I'm always tempted to replace it with the line "b = t". There's already an implicit cast to bool, why mince semantics?Melisa
as the Q says, because b=t gives a warningAnarthrous
interesting how many people are against !! on subjective basis. double negation is the idiomatic cast-to-bool vehicle in JavaScript, and if javascripters get it, I'd expect C++ users would too.Shackleford
double negation is common in most of the scripting languages https://mcmap.net/q/24603/-what-does-mean-in-ruby So, usage in a high level, understandable code(at least by writer himself) is stricly prohibited.. :)Audible
@GregD One case would be when assigning value to a bit-field flag in a struct. Your solution would truncate (at least in some compilers), while the rest offered here would set the flag to the relevant truth value. Assuming that the compiler will do the right thing (for you) is not the smart thing. And setting the bit-field type to boolean doesn't change this (at least with the compiler I'm dealing with). Undefined behaviour.Jordan
@GregD b = t ? true : false; has an explicit cast of t to bool. b = t; has an implicit cast. Although I prefer b = static_cast<bool>(t); when I have to be explicitArgyrol
C
84

The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for

b = (t != 0);

No implicit conversions.

Check answered 15/10, 2008 at 20:7 Comment(0)
S
42

Alternatively, you can do this: bool b = (t != 0)

Shirleenshirlene answered 15/10, 2008 at 19:39 Comment(2)
I always use this one because I think it most clearly expresses the intent. It's effectively what the compiler is doing in the case that generates the warning, but is explicit about it. The !! seems hacky to me.Pitiless
Doesn't work if t is an object whose class provides operator (bool), whereas the other suggestions do.Ervin
K
33

Careful!

  • A boolean is about truth and falseness.
  • An integer is about whole numbers.

Those are very distinct concepts:

  • Truth and falseness is about deciding stuff.
  • Numbers are about counting stuff.

When bridging those concepts, it should be done explicitly. I like Dima's version best:

b = (t != 0);

That code clearly says: Compare two numbers and store the truth-value in a boolean.

Kuehl answered 15/10, 2008 at 20:35 Comment(0)
A
7


Yes it is safe.


0 is interpreted as false, everthing else is true,
hence !5 comes out as a false
!0 comes out as true
so !!5 comes out as true

Adila answered 15/10, 2008 at 19:41 Comment(0)
O
6

All valid techniques, all will generate the same code.

Personally, I just disable the warning so I can use the cleanest syntax. Casting to a bool is not something I'm worried about doing accidentally.

Overall answered 15/10, 2008 at 19:38 Comment(7)
Yeah, thank Microsoft for giving us warnings for clear and idiomatic C code.Lorraine
I do wonder what made them add the warning; someone must've been doing something really dumb...Overall
maybe it has implications on certain target architectures? MS doesn't say other than the warning for normal casts and conversions is "by design"Anarthrous
@MikeF the warning is there so the compiler can "WARN" you about something you might not be intending to do. disabling the warning might be "clean" but might result to typos or unintented errors. (like passing a long to a function that wanted a bool?)Ojibwa
I recently saw a piece of code that intended to compare two pointers, but in fact the pointers were implicitly cast into bool, so you may guess it did not work very well. I am against blanket disabling of warnings unless there is a compiler bug involved (as was the case with some VC++ 6.0 warnings)Ringdove
The warning is quite useful when you by mistake assigned the integer a to b instead of the boolean c to b.Maroney
@Anarthrous It says the warning for an explicit cast is the same as an implicit cast "by design". The warning is there because simply casting to boolean is bad programming practice. Converting to boolean using a bool b = (a != 0) communicates exactly your intent. Casting to boolean may bypass having to worry about the type, but causes maintainability issues.Uri
S
6

I would not use:

bool b = !!t;

That is the least readable way (and thus the hardest to maintain)

The others depend on the situation.
If you are converting to use in a bool expression only.

bool b = t ? true : false;
if (b)
{
    doSomething();
}

Then I would let the language do it for you:

if (t)
{
    doSomething();
}

If you are actually storing a boolean value. Then first I would wonder why you have a long in the first places that requires the cast. Assuming you need the long and the bool value I would consider all the following depending on the situation.

bool  b = t ? true : false;      // Short and too the point.
                                 // But not everybody groks this especially beginners.
bool  b = (t != 0);              // Gives the exact meaning of what you want to do.
bool  b = static_cast<bool>(t);  // Implies that t has no semantic meaning
                                 // except as a bool in this context.

Summary: Use what provides the most meaning for the context you are in.
Try and make it obvious what you are doing

Seemaseeming answered 15/10, 2008 at 20:10 Comment(2)
the "let the language do it" (aka 'usual conversions') is what generates the warning. an example of when this might be necessary: struct C { void * hdl; void * get_hdl() { return hdl; } bool has_hdl() const { return hdl ? true : false; }Anarthrous
readability is in the eye of the beholder. for example, I consider prefix operators more readable than postfix operators, conciseness over verbosity, and dryness over duplication. (double) negation is a prefix operator (win), is shorter than the ternary (win), and can be perceived as a single operator whereas the ternary carries three distinct expressions (plus the operator syntax).Shackleford
H
4

Comparison to 0 doesn't work so well. Which comes back -- why !! vs. ternary?

class foo { public: explicit operator bool () ; };

foo f;

auto a = f != 0; // invalid operands to binary expression ('foo' and 'int')
auto b = f ? true : false; // ok
auto c = !!f; // ok
Highlands answered 25/5, 2018 at 6:39 Comment(2)
Is there any distinctive new information in this answer? If you decide to answer an older question that has well established and correct answers, adding a new answer late in the day may not get you any credit. If you have some distinctive new information, or you're convinced the other answers are all wrong, by all means add a new answer, but 'yet another answer' giving the same basic information a long time after the question was asked usually won't earn you much credit.Spathose
Yes. Nobody else identified that != 0 can often fail.Highlands
V
3

I recommend never suppressing that warning, and never using a c cast (bool) to suppress it. The conversions may not always be called as you assume.

There is a difference between an expression that evaluates to true and a boolean of that value.

Both !! and ternary take getting used to, but will do the job similarly, if you do not want to define internal types with overloaded casts to bool.

Dima's approach is fine too, since it assigns the value of an expression to a bool.

Visceral answered 15/10, 2008 at 19:45 Comment(7)
Care to come up with an example where that warning would help in any way?Overall
well, you might be losing information in that cast. maybe you're porting the code from an environment in which no information is lost in this conversion. in that case, may you'd like to know about any lost bits.Schafer
Of course you're losing information. That's the entire point of converting to bool!Honk
@wilhelmtell: What kind of environment doesn't lose information in int->bool?Overall
@Mike: as code changes, the value you are converting to bool could be typedef'd, and thus the code generated might change. Also, there are compilers with signed and unsiged char as default, which could give different results.Visceral
@tabdamage: The type you're converting to bool has no effect on whether or not you get this warning, so that example doesn't work. And char signdness has no bearing on anything.Overall
MS says (msdn.microsoft.com/en-us/library/b6801kcy.aspx) the warning is "by design" but they don't explainAnarthrous
D
2

If you're worried about the warning, you can also force the cast: bool b = (bool)t;

Drifter answered 15/10, 2008 at 19:40 Comment(8)
actually that is exactly equivalent to bool b = t; and generates the same warningAnarthrous
Don't use C casts. C++ casts are there for a reason. Also, I didn't try this on my compiler, but I wouldn't expect it to generate any warning because you are explicitly asking the compiler to do something. Compilers usually only warn you when something implicit happens.Schafer
I never see the warning under GCC on my Ubuntu box when doing it this wayDrifter
@wilhelmtell: Give it a try; you'll find that VC++ does in fact warn you about '(bool)a', 'bool(a)' and 'static_cast<bool>(a)'.Overall
@warren: Ah, the poster didn't mention that this is VC++ specific, tags edited accordingly.Overall
Q is not necessarily VC++ specific (although that is where I tested it), I'm asking about the diff (if any) between !!x and x?true:false. I bet many compilers have similar warnings depending on your warning level. removed visualstudio tagAnarthrous
@jwfeam: If that's the question then you got your answer yonks ago (="no, there's no difference"). BTW, you'd lose the bet about other compilers emitting this (rather weird) warning.Overall
@Mike F, you may be right, this could be a VC++ specific warning. Since I don't have access to all C++ compilers, I can only guess. But the Q isn't really about the warning, it was "is !! safe?". I posted a separate Q about the warning (and got some good answers too).Anarthrous
B
2

I really hate !!t!!!!!!. It smacks of the worst thing about C and C++, the temptation to be too clever by half with your syntax.

bool b(t != 0); // Is the best way IMHO, it explicitly shows what is happening.

Bushelman answered 15/10, 2008 at 21:8 Comment(0)
L
1

!! may be compact, but I think it is unnecessarily complicated. Better to disable the warning or use the ternary operator, in my opinion.

Lorraine answered 15/10, 2008 at 19:44 Comment(0)
T
0

I would use b = (0 != t) -- at least any sane person can read it easily. If I would see double dang in the code, I would be pretty much surprised.

Tackett answered 15/10, 2008 at 19:50 Comment(0)
R
0

Disable the warning.

Write for clarity first; then profile; then optimize for speed, where required.

Ruttger answered 15/10, 2008 at 22:20 Comment(0)
Z
0

!! is only useful when you're using a boolean expression in arithmetic fashion, e.g.:

c = 3 + !!extra; //3 or 4

(Whose style is a different discussion.) When all you need is a boolean expression, the !! is redundant. Writing

bool b = !!extra;

makes as much sense as:

if (!!extra) { ... }
Zena answered 15/10, 2008 at 23:58 Comment(0)
A
0

One important reason of using the double negation technique, which no one yet mentioned, is performance. As it was pointed out this is basically a replacement of the

x = b ? 1 : 0;

statement, which may add substantial overhead if it evaluates to true in roughly half of the cases. CPU branch-prediction will not work well in such a situation, which would lead to branch misses quite often. Due to this the overhead compared with using

x = !!(b);

operation would be quite substantial, provided, of course, that this operation is executed sufficiently often.

Acrodrome answered 24/4, 2023 at 21:59 Comment(0)
C
-1

I recommend to use

if (x != 0)

or

if (x != NULL)

instead of if(x); it's more understandable and readable.

Courbevoie answered 15/10, 2008 at 20:31 Comment(1)
To me if(x) is more readable. It says if not zero in the most concise way.Kristoforo
R
-2

The double not feels funny to me and in debug code will be very different than in optimized code.

If you're in love with !! you could always Macro it.

#define LONGTOBOOL(x) (!!(x))

(as an aside, the ternary operator is what I favor in these cases)

Reardon answered 15/10, 2008 at 19:45 Comment(0)
C
-4

I would use bool b = t and leave the compile warning in, commenting on this particular line's safety. Disabling the warning may bite you in the butt in another part of the code.

Cohleen answered 15/10, 2008 at 20:25 Comment(2)
Leaving warnings that need to be ignored is counter productive; it leads you to miss other, more important warnings. A zero-warning policy is the best.Gerita
Yes, but disabling warnings is worse, it shuts down warnings that may be more important. As Edgar said above, bools are about truth-value, integers are about number. That distinction should be preserved somehow.Cohleen

© 2022 - 2024 — McMap. All rights reserved.