473,480 Members | 2,277 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Bit field structures and C++

Hi,

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.

In fact, the compilers also translate the following structure without
warning:

struct X
{ bool f1:2;
bool f2:2;
};
If the code at the top is valid I would like to prefer this over
enumeration types with the usual power of two values.

Unfortunately at least gcc seems not to optimize expressions like
if (x.f2)
in a way to avoid the logical shift.
Marcel
Oct 20 '08 #1
6 4189
On 2008-10-20 19:09, Marcel Müller wrote:
Hi,

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.
C++ allows bool bitfields.
In fact, the compilers also translate the following structure without
warning:

struct X
{ bool f1:2;
bool f2:2;
};
If the code at the top is valid I would like to prefer this over
enumeration types with the usual power of two values.

Unfortunately at least gcc seems not to optimize expressions like
if (x.f2)
in a way to avoid the logical shift.
I doubt that there is any way to implement a bitfield without the shift,
and often also masking.

--
Erik Wikström
Oct 20 '08 #2
Erik Wikström wrote:
C++ allows bool bitfields.
OK, thanks.

>Unfortunately at least gcc seems not to optimize expressions like
if (x.f2)
in a way to avoid the logical shift.

I doubt that there is any way to implement a bitfield without the shift,
and often also masking.
In the above case: yes.

If I had implemented the same semantic by an enumeration type, the
condition above would look like
enum Y
{ f1 = 1,
f2 = 2,
};
Y y;
if (y & Y::f2)
or similar. This does not require a shift operation, of course. In the
same way a compiler could optimize the condition
if (x.f2)
by using a mask and a comparsion to zero.
Btw. gcc really does more complex optimizations. E.g. the initial code
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;
}

is in fact translated as
int main(int argc, char* argv[])
{ X x;
x.f1 = true;
x.f2 = false;
printf("%u %u %u\n", 1, 0, 1);
return 0;
}
So gcc realized that x.f1 and x.f2 are in fact constant at the execution
of printf. The same applies to 'if' unless I put it into a subfunction
with an X& argument.
Marcel
Oct 20 '08 #3
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:ja*********@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
Oct 20 '08 #4
In article <48***********************@newsspool4.arcor-online.net>,
=?ISO-8859-1?Q?Marcel_M=FCller?= <ne**********@spamgourmet.orgwrote:
Hi,

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);
[...]

BTW, you're passing a size_t where printf() expects an unsigned int. On
machines where size_t is a larger type, like unsigned long, this will
yield undefined behavior. Cast the sizeof to an unsigned int, or use a
type-safe facility like iostream.
Oct 20 '08 #5
On 2008-10-20 18:32:29 -0400, bl********@gishpuppy.com (blargg) said:
In article <48***********************@newsspool4.arcor-online.net>,
=?ISO-8859-1?Q?Marcel_M=FCller?= <ne**********@spamgourmet.orgwrote:
>Hi,

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);
[...]

BTW, you're passing a size_t where printf() expects an unsigned int. On
machines where size_t is a larger type, like unsigned long, this will
yield undefined behavior. Cast the sizeof to an unsigned int, or use a
type-safe facility like iostream.
Or use "%zu" for the format specifier, if your version of printf supports C99.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Oct 21 '08 #6
On Oct 21, 12:32 am, blargg....@gishpuppy.com (blargg) wrote:
In article <48fcbb41$0$13388$9b4e6...@newsspool4.arcor-online.net>,
=?ISO-8859-1?Q?Marcel_M=FCller?= <news.5.ma...@spamgourmet.orgwrote:
Hi,
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);
[...]
BTW, you're passing a size_t where printf() expects an
unsigned int. On machines where size_t is a larger type, like
unsigned long, this will yield undefined behavior.
Formally, it has nothing to do with the size of size_t per se.
size_t is a typedef; if it is defined to be unsigned long, you
have undefined behavior, even if the sizes are the same.
Cast the sizeof to an unsigned int, or use a type-safe
facility like iostream.
--
James Kanze (GABI Software) email:ja*********@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
Oct 21 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
20300
by: Vladimir | last post by:
Hello, I have a table in MS Access database. It has one field (with BYTE datatype) that has several properties set in Lookup tab of table Design View. Display Control = Combo Box. Row Source...
11
3437
by: Bradford Chamberlain | last post by:
I work a lot with multidimensional arrays of dynamic size in C, implementing them using a single-dimensional C array and the appropriate multipliers and offsets to index into it appropriately. I...
9
5356
by: Skybuck Flying | last post by:
Hello, What does Const mean in this c structure ? and what is the delphi equivalent ? I think const struct just means it can't be modified... is that correct ? Struct { Type1 Field1;...
2
1160
by: sushant | last post by:
is it possible to scan a value to a member of a stucture which is of bit field type??? if yes then how if no then why....
2
2387
by: thomasfarrow | last post by:
At work, our development team has a development standards document that insists Structures should never be used. I'm looking to change this standard but need a suitable argument in order to make...
39
3182
by: windandwaves | last post by:
Hi Folk I have to store up to eight boolean bits of information about an item in my database. e.g. with restaurant drive-through facility yellow windows
17
3997
by: The Frog | last post by:
Hello everyone, I am working on an application that can build database objects in MS Access from text files. I suppose you could call it a backup and restore type routine. Accessing the...
4
1463
by: colin | last post by:
How can I access a field contained in fieldInfo by reference so I can pass it to a function ? ive tried __refvalue but this needs a type known at compile time, I can access it with SetValue and...
4
1702
by: eBob.com | last post by:
In my class which contains the code for my worker thread I have ... Public MustInherit Class Base_Miner #Region " Delegates for accessing main UI form " Delegate Sub DelegAddProgressBar(ByVal...
4
1541
by: Adrian20XX | last post by:
Hi, Hi, I have a typedefed struct, and later when I declare multiple const structures and want to use a field of one in an inialization, I get the following error: "error C2099: initializer is not...
0
7048
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6911
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
5344
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4787
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4488
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
2999
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
564
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
185
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.