Is !! a Safe Way to Convert to Bool in C++

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

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.

Casting int to bool in C/C++

0 values of basic types (1)(2)map to false.

Other values map to true.

This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.


It's a common error to assume that as function return values, false indicates failure. But in particular from main it's false that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.


There's no need to cast to bool for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x, works nicely. One can read !! as a “convert to bool” operator, much as --> can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)



1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”

2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”

What is the performance implication of converting to bool in C++?

I was puzzled by this behaviour, until I found this link:

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633

Apparently, coming from the Microsoft Developer who "owns" this warning:

This warning is surprisingly
helpful, and found a bug in my code
just yesterday. I think Martin is
taking "performance warning" out of
context.

It's not about the generated code,
it's about whether or not the
programmer has signalled an intent to
change a value from int to bool
.
There is a penalty for that, and the
user has the choice to use "int"
instead of "bool" consistently (or
more likely vice versa) to avoid the
"boolifying" codegen. [...]

It is an old warning, and may have
outlived its purpose, but it's
behaving as designed here.

So it seems to me the warning is more about style and avoiding some mistakes than anything else.

Hope this will answer your question...

:-p

Why use !! when converting int to bool?

The problems with the "!!" idiom are that it's terse, hard to see, easy to mistake for a typo, easy to drop one of the "!'s", and so forth. I put it in the "look how cute we can be with C/C++" category.

Just write bool isNonZero = (integerValue != 0); ... be clear.

How do I safely cast a System.Object to a `bool` in C#?

There are two options... with slightly surprising performance:

  • Redundant checking:

    if (rawValue is bool)
    {
    bool x = (bool) rawValue;
    ...
    }
  • Using a nullable type:

    bool? x = rawValue as bool?;
    if (x != null)
    {
    ... // use x.Value
    }

The surprising part is that the performance of the second form is much worse than the first.

In C# 7, you can use pattern matching for this:

if (rawValue is bool value)
{
// Use value here
}

Note that you still end up with value in scope (but not definitely assigned) after the if statement.

C++: avoid automatic conversion of string to bool in overloads

You could add an template overload that takes a reference to array of char of size N where N is a template parameter, and/or one that accepts a const char*.

template <std::size_t N>
static void printValue(sts::ostringstream& out, const char (&str)[N])
{
out << str;
}

What is the preferred way in C++ for converting a builtin type (int) to bool?

There is no preferred way in C++, since the C++ Std simply allows the integral conversion from int to bool. (So the preferred way wrt the Std would be bool b = i;.)

That said, judging from the other answers, there does not even seem to be an accepted way to do it in Visual C++ (MS) although the MSDN page states

... If you cannot rewrite the expression
to use type bool, then you can add
"!=0" to the expression, which gives
the expression type bool. ...

So one might conclude that MS recommends to use the !=0 comparison, although I, personally, think it's the worst of all the warning-supressing alterantives presented in the question and the answers here: The "type" in the source code is BOOL, and even though it's really just an int at least one should compare a "BOOL" with !=FALSE like has been proposed in some other answers.

Convert string to boolean in C#

I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands

OP, you can convert a string to type Boolean by using any of the methods stated below:

 string sample = "True";
bool myBool = bool.Parse(sample);

// Or

bool myBool = Convert.ToBoolean(sample);

bool.Parse expects one parameter which in this case is sample, .ToBoolean also expects one parameter.

You can use TryParse which is the same as Parse but it doesn't throw any exception :)

string sample = "false";
Boolean myBool;

if (Boolean.TryParse(sample , out myBool))
{
// Do Something
}

Please note that you cannot convert any type of string to type Boolean because the value of a Boolean can only be True or False

Hope you understand :)

How can I fix an int-to-bool warning in C++?

How about

accessLV[i] = FileRead(file1, i + 1) != 0;


Related Topics



Leave a reply



Submit