double/int/string to bool in c++

Q:

int main(void) {
  using namespace std;
  vector<bool> a;
  a.push_back("asdf");
  a.push_back("");  
  a.push_back(12);  
  a.push_back(0.0);  
  copy(a.begin(), a.end(), ostream_iterator<bool>(cout, "\n"));
  return 0;
}

Pointers and integers, and also booleans, are integral types. The first three are all either pointers or integers, and since they are all non-zero, they convert to the boolean value true. The fourth value of type double converts to a zero integral value and hence false.

Conversion of doubles that are not representable as integral values (like infinity and NaN) is undefined.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s