Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

boolean - Automatic conversion from double/int/string to bool in C++

I'm a Java programmer who has been trying to learn a bit of C++ on the side to expand on my knowledge. Here is a small code snippet which I think works due to implicit conversion but I'd like to know which part of the specification does it refer to and what are the other rules which I must be aware of when it comes to implicit conversion. Is there a document/link/site out there which lays down the implicit conversion rules?

#include <vector>
#include <iostream>
#include <iterator>

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, "
"));
  return 0;
}

/*
output:

1
1
1
0
*/

TIA,
sasuke

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

See 4.9 for details, and also 4.12 for "Boolean conversions":

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

Your 0.0 is an arithmetic type of zero value.

Perhaps you may not be familiar with string literals in C++: "" denotes the array char[1] { 0 }, and this array (of one element) decays to a pointer to its first element, which is necessarily a non-null pointer. Similarly, "asdf" denotes an array char[5] { 'a', 's', 'd', 'f', 0 }, and again this decays to a (non-null) pointer to its first element. The actual value of the characters is entirely immaterial.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...