neeru
neeru

Reputation: 259

structure definition and initialisation

I've a structure like this

typedef struct mystruct{
    char* name;
    int age : 5;
}instr;

int main(){
    instr object1={.name= "tiny",.age=20};
    printf("%d and %d\n",object1.age);
    return 0;
}

what is the meaning of the line
int age : 5 in the stucture definition?

For lower values, instead of 5 here, I get compilation warning

overflow in implicit constant conversion [-Woverflow]

Upvotes: 1

Views: 121

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

A signed 5-bit integer (as defined by your int age : 5; bit-field) can hold values in the range -16 .. +15, but 20 is outside this range.

Use unsigned int or use 6 or more bits. Actually, people can be old enough to need 7 bits unsigned or 8 bits signed.

Bit-fields are curious parts of the language. I doubt if you will benefit from using one for age as here. You might use a char value of some sort, though you won't be wasting space in the structure even if you use an int (it will have a size of 8 bytes on 32-bit machines, and probably 16 bytes on 64-bit machines).

In ISO/IEC 9899:2011, §6.7.2.1 Struct and union specifiers, footnote 125 says:

125) As specified in 6.7.2 above, if the actual type specifier used is int or a typedef-name defined as int, then it is implementation-defined whether the bit-field is signed or unsigned.

It appears from the warning message you got that plain int bit-fields with your compiler are signed. You should be explicit about whether you want the type to be signed int or unsigned int.

Upvotes: 1

Related Questions