Ask Your Question
4

How come const char* is automatically transformed to bool instead of std::string?

asked 2022-01-16 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-28 19:00:00 +0000

bukephalos gravatar image

In C++, a const char* can be used as a boolean value because it can be either null or not null. If the pointer is null, it is equivalent to false, and if it points to a non-null value, it is equivalent to true. This behavior is inherited from C, where null pointers are used to indicate errors or uninitialized values.

On the other hand, transforming a const char* to a std::string requires an explicit conversion, as the two types are not directly related. While it is possible to implicitly convert a const char* to a std::string in some cases, it is generally discouraged for clarity and readability reasons. It is better to use an explicit conversion, such as using the std::string constructor that takes a const char* as an argument.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-16 11:00:00 +0000

Seen: 11 times

Last updated: May 28 '21