Conversion of char * to bool

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

I have compiled the following program with two different
implementations without any warnings at all. Why is a char *
converted to a bool (apparently) without a cast?

void foo( bool a ) {}

int main() {
foo( "123" );
const char *bar="123";
foo( bar );
return 0;
}
 
T

TB

Christopher Benson-Manica sade:
I have compiled the following program with two different
implementations without any warnings at all. Why is a char *
converted to a bool (apparently) without a cast?

Because the C++ Standard allows it. It's convenient.
A zero arithmetic value or null pointer value is converted to false,
everything else to true.
void foo( bool a ) {}

int main() {
foo( "123" );
const char *bar="123";
foo( bar );
return 0;
}

TB
 
C

Christopher Benson-Manica

TB said:
Because the C++ Standard allows it. It's convenient.

I disagree wholeheartedly WRT the "convenience" of this behavior. I
spent some time tracking down some bizarre behavior that turned out to
be caused by a change in the prototype of a function from

void foo( const char *, const char * );

to

void foo( const char *, bool, const char * );
A zero arithmetic value or null pointer value is converted to false,
everything else to true.

What would have been so complicated about

foo( "foo", myCharPtr != NULL );

?
 
B

Bo Persson

Christopher Benson-Manica said:
I disagree wholeheartedly WRT the "convenience" of this behavior.

All too true!

The convenience comes for old C from before the appearance of the bool
type. Traditionally any expression could be used as a condition value,
treating zero as false and non-zero as true.

Unfortunately, there is way too much old code out there, for anyone to
dare to change this rule.


Bo Persson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top