Hi,

Can somebody please explain , printing with structure variable also working.

int main( void ) {
    struct bitfs {
        unsigned char a:4;
        unsigned int  b:5;
    };
    struct bitfs bf = {15,31};

    struct bitfs2 {
        unsigned char a:4;
        unsigned int  b:5;
    }bf2 = {15,31};

    printf("a= %u \n", bf.a);
    printf("b= %u \n", bf.b);

    printf("a2= %u \n", bf2.a);
    printf("b2= %u \n", bf2.b);


    printf("a2= %u \n", bf2);/*how is this also working*/

return 0;
}

Recommended Answers

All 5 Replies

its a garbage value i guess!!

It's not "working". When you lie to printf() you invoke undefined behavior, which could result in a seemingly valid value being printed.

Some compilers check the types of printf()'s arguments against the types in the format string and give an error or warning message if they don't match. That's always a good feature to enable, if it's available.

But assuming you're not compiling this for something like an 8051 microcontroller, the bf2 struct will be pushed on the stack and will occupy the spot where printf() will look for an unsigned int for "%u". So it'll print whatever's there. But as the others have indicated, it might not be what's expected.

Personally, I've been burnt by bitfields, so I never, ever use them. The problem is that different compilers implement them differently--even different endianly on the same processor.

Thanks for the replies.

Some compilers check the types of printf()'s arguments against the types in the format string and give an error or warning message if they don't match. That's always a good feature to enable, if it's available.

Does anybody have any idea how to enable the feature.I am using the GCC compiler on linux.
I tried googling but helpless.

Try the documentation for the compiler.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.