views:

2668

answers:

17

[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.

+4  A: 

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.

Yeah, thank Microsoft for giving us warnings for clear and idiomatic C code.
Kristopher Johnson
I do wonder what made them add the warning; someone must've been doing something *really* dumb...
maybe it has implications on certain target architectures? MS doesn't say other than the warning for normal casts and conversions is "by design"
jwfearn
@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?)
moogs
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)
Gorpik
The warning is quite useful when you by mistake assigned the integer a to b instead of the boolean c to b.
Anders Sandvig
+27  A: 

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

Dima
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.
rmeador
+3  A: 

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

warren
actually that is exactly equivalent to bool b = t; and generates the same warning
jwfearn
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.
wilhelmtell
I never see the warning under GCC on my Ubuntu box when doing it this way
warren
@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)'.
@warren: Ah, the poster didn't mention that this is VC++ specific, tags edited accordingly.
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 tag
jwfearn
@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.
@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).
jwfearn
+1  A: 


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

EvilTeach
+1  A: 

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

Kristopher Johnson
A: 

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)

plinth
+4  A: 

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.

tabdamage
Care to come up with an example where that warning would help in any way?
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.
wilhelmtell
Of course you're losing information. That's the entire point of converting to bool!
John Millikin
@wilhelmtell: What kind of environment doesn't lose information in int->bool?
@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.
tabdamage
@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.
MS says (http://msdn.microsoft.com/en-us/library/b6801kcy.aspx) the warning is "by design" but they don't explain
jwfearn
+3  A: 

Wrap it inside an inline function wiht a descriptive name! (and don't use a #define! The function has no overhead either).

template <typename T>
inline bool make_bool(T value) {
    return value ? true : false;
    // or, if you prefer,
    // return !!value;
}

Don't try to be too clever in code. It might come back to bite you.

/EDIT: although in the particular case of bool I must agree with some others: this is idiomatic C++ (although I don't like it). Disabling the warning might be the way to go.

Konrad Rudolph
Really? One could say you are re-inventing static_cast<bool> here.
Martin York
@Martin: Well, since the OP claims that `static_cast` does *not* avoid the warning, I hardly reinvent it.
Konrad Rudolph
indeed static_cast does NOT void the warning.
jwfearn
good answer, this is what I will do
jwfearn
While you're at it (making your code explicit), call the function something less generic than "make_bool" and use something that conveys the actual purpose. But then, you're better off with just "bool hasItems = count > 0" instead of using a "inline bool hasItems(long count)" function.
Ates Goral
A: 

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.

+39  A: 

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.

fizzer
And readable too.
Vulcan Eager
+5  A: 

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

Martin York
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; }
jwfearn
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).
just somebody
A: 

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.

Paul Nathan
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.
Mark Ransom
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.
Paul Nathan
+1  A: 

I recommend to use

if (x != 0)

or

if (x != NULL)

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

Marco M.
+17  A: 

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.

edgar.holleis
+1  A: 

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.

Jim In Texas
A: 

Disable the warning.

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

Jay Bazuzi
A: 

!! 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) { ... }
aib