F
Fao, Sean
I was just thumbing through K&R 2nd Edition and thought I'd read up on
bit-fields, which I [personally] haven't had much use for in my career.
Anyhow, K&R says that, "Fields may be declared only as ints; for
portability, specify signed or unsigned explicitly". So it got me
wondering what would happen if I tried to declare a field as a short
rather than an int.
I compiled my code with GCC 3.3.6 with all warning turned on and I got
no warnings returned. Have things changed since K&R or is there
something bad about my code?
On my implementation, the sizeof() each bit-field is identical to the
type I used to declare the fields.
<code>
#include <stdio.h>
struct {
unsigned short admin : 1;
unsigned short manager : 1;
unsigned short supervisor : 1;
unsigned short user : 1;
unsigned short guest : 1;
} roles;
struct {
unsigned int admin : 1;
unsigned int manager : 1;
unsigned int supervisor : 1;
unsigned int user : 1;
unsigned int guest : 1;
} roles2;
int main(void)
{
printf("sizeof(short): %d sizeof(roles): %d\n",
sizeof(short), sizeof(roles));
printf("sizeof(int): %d sizeof(roles2): %d\n",
sizeof(int), sizeof(int));
return 0;
}
</code>
Just curious...
Thank you in advance,
bit-fields, which I [personally] haven't had much use for in my career.
Anyhow, K&R says that, "Fields may be declared only as ints; for
portability, specify signed or unsigned explicitly". So it got me
wondering what would happen if I tried to declare a field as a short
rather than an int.
I compiled my code with GCC 3.3.6 with all warning turned on and I got
no warnings returned. Have things changed since K&R or is there
something bad about my code?
On my implementation, the sizeof() each bit-field is identical to the
type I used to declare the fields.
<code>
#include <stdio.h>
struct {
unsigned short admin : 1;
unsigned short manager : 1;
unsigned short supervisor : 1;
unsigned short user : 1;
unsigned short guest : 1;
} roles;
struct {
unsigned int admin : 1;
unsigned int manager : 1;
unsigned int supervisor : 1;
unsigned int user : 1;
unsigned int guest : 1;
} roles2;
int main(void)
{
printf("sizeof(short): %d sizeof(roles): %d\n",
sizeof(short), sizeof(roles));
printf("sizeof(int): %d sizeof(roles2): %d\n",
sizeof(int), sizeof(int));
return 0;
}
</code>
Just curious...
Thank you in advance,