jeudi 22 janvier 2015

Are conditional expressions in C++ always of bool type?

In C conditional-oriented operators evaluate to either 1 or 0 of type int (even if it does have dedicated _Bool type). Referring to C11 N1570 draft:



C11 §6.5.8/6 Relational operators


Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.107) The result has type int.


C11 §6.5.9/3 Equality operators


The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence.108) Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int. For any pair of operands, exactly one of the relations is true.


C11 6.5.13/3 Logical AND operator


The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.


C11 6.5.14/3 Logical OR operator


The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.



As I checked C++ seems to be different in this matter, as in following example (see http://ift.tt/1t20IP1):



#include <iostream>
#include <typeinfo>

int main() {
double x = 10.0;

std::cout << typeid(x <= 10.0).name() << std::endl;

return 0;
}


outputs b, which as I guess indicates bool type. Does C++ guarantee that all of these operators always evaluate to bool type (in contrast to C)?


Aucun commentaire:

Enregistrer un commentaire