James Kanze
10/20/2008 7:56:00 PM
On Oct 20, 7:09 pm, Marcel Müller <news.5.ma...@spamgourmet.org>
wrote:
> is the following code valid?
> #include <stdio.h>
> struct X
> {
> bool f1:1;
> bool f2:1;
> };
> int main(int argc, char* argv[])
> {
> X x;
> x.f1 = true;
> x.f2 = false;
> printf("%u %u %u\n", x.f1, x.f2, sizeof x);
> return 0;
> }
> While all my compiler seem to eat the combination of bool and
> bit fields, it is not that straight forward, because normally
> it must be an unsigned integer type. And there is no implicit
> conversion from that to bool.
No implicit conversion of what to bool? In this case, you're
passing a type bool as a vararg. In C++, bool is an integral
type, so integral promotions apply---the actual argument will be
passed as an int with value of either 0 or 1. In C (and I'm
pretty sure in C++ as well), int's and unsigned int's with the
same values have the same representation, and this special case
of type mismatch is legal. (Note that if you passed a negative
value, it would be undefined behavior.)
Of course, in this particular case, C++ offers better
alternatives:
std::cout << x.f1 << ' ' << x.f2 ...
> In fact, the compilers also translate the following structure
> without warning:
> struct X
> {
> bool f1:2;
> bool f2:2;
> };
Why shouldn't it?
> If the code at the top is valid I would like to prefer this
> over enumeration types with the usual power of two values.
But they don't do the same thing.
> Unfortunately at least gcc seems not to optimize expressions
> like
> if (x.f2)
> in a way to avoid the logical shift.
That sounds like a problem with the optimizer. I'd ask about it
in a g++ newsgroup, or even post it as a bug report (or an
enhancement request).
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34