boolean to integral conversion

N

Neelesh Bodas

Can somebody please explain the fine difference between these two
clauses of the standard:

4.5 (Integral promotions)
4. An rvalue of type bool can be converted to an rvalue of type
int, with false becoming zero and true becoming one


4.7 (Integral conversions)
4. If the source type is bool, the value false is converted to zero
and the value true is converted to one.

Thus, is bool-to-int an integral promotion or integral conversion?

void foo(const int&);
void bar(int);
bool b = false;

int i = false; // here?
foo(b); // here?
bar(b); //here?

-Neelesh
 
J

James Kanze

Can somebody please explain the fine difference between these two
clauses of the standard:
4.5 (Integral promotions)
4. An rvalue of type bool can be converted to an rvalue of type
int, with false becoming zero and true becoming one
4.7 (Integral conversions)
4. If the source type is bool, the value false is converted to zero
and the value true is converted to one.

Integral promotions always occur in a certain number of cases,
whether they are needed or not. Integral conversions only occur
if needed. Thus:

short s1,s2 ;
long l1 ;

l1 = s1 + s2 ;

Both s1 and s2 are converted to int (integral promotion),
although there's not an int in sight, and not real reason (other
than the standard says so) for the conversion. The result (an
int) is converted to long (integral conversion) because a long
is what is needed; otherwise, it would remain an int.
Thus, is bool-to-int an integral promotion or integral conversion?

Integral promotion:

bool b1 = true, b2 = true ;
std::cout << b1 + b2 << std::endl ;

should output 2, because as an operator to an arithmetic operand
in an expression, integral promotion occurs, the addition is
done on int's, and the result is an int (not a bool!). Also
note:

std::cout << std::boolalpha << ! true << std::endl ;
std::cout << std::boolalpha << ~ true << std::endl ;

In the first, there is a logical operation, everything takes
place as a bool, and a bool is output. In the second, the ~
operator forces integral promotion, the results are int, and are
output as such.
void foo(const int&);
void bar(int);
bool b = false;
int i = false; // here?
foo(b); // here?
bar(b); //here?

These are all conversions. But a promotion is also a
conversion, and will be used as such.

Note that the distinction also affects operator overload
resolution. A promotion is a better match than other
conversions.
 

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

No members online now.

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,805
Latest member
ClydeHeld1

Latest Threads

Top