Mail Archives: djgpp/1998/01/14/03:37:16
Noam Rotem <nrotem AT johnbryce DOT co DOT il> wrote:-
> When I use bit fields within a struct, initialize them and print the values,
> I get undefined non zero values. For example:
> struct {int x : 1; int y : 1; int z : 1; }
> Test={0,0,0};
> main() {
> ....
> Test.x=1; printf("%d",Test.x);
> ... }
> I usually get -1 as an output, or other non zero values. ...
A field declared as `int x:1;' has only one bit. As that field is in a
signed mode, that bit is the sign bit, and if that bit is set, the value is
treated as -1. If you want a field `int x:N;' to contain values from 0 to
pow(2,N)-1, you must declare the field as `unsigned int x:N;'.
If a program contains the words `unsigned' and `register' a lot, I find it
useful to put these lines at the top of the program file:-
#define uns unsigned
#define reg register
- Raw text -