Gaurang Tandon
Gaurang Tandon

Reputation: 6753

finding the output of a c program

I'm preparing myself for placement and these days solving C programming questions . My code is:

#include<stdio.h>

int main()
{
    struct value
    {
        int bit1:1;
        int bit3:4;
        int bit4:4;
    }bit={1, 2, 13};

    printf("%d, %d, %d\n", bit.bit1, bit.bit3, bit.bit4);
    return 0;
}

I'm stuck with this structure . I thought the answer would be : 1,4,4 but the output is : -1,2,-3 Please explain this question. Thanks.

Upvotes: 0

Views: 202

Answers (4)

haccks
haccks

Reputation: 105992

On compilation it is generating:

[Warning] overflow in implicit constant conversion [-Woverflow]  

and that's why you are getting

 -1,2,-3  

as output.
Note: Always use debugger and debug your program.

Upvotes: 2

CRAFTY DBA
CRAFTY DBA

Reputation: 14915

The :1, :4, :4 is confusing the compiler. Here is a quick link to the structures.

http://en.wikipedia.org/wiki/Struct_(C_programming_language)

A cleaner programming style is to define the structure separately and instantiate it on another line.

/*
  simple1.c - a program to demonstrate c structures.
*/

// Standard libraries
#include <stdio.h>

int main()
{
    // Definition
    struct value
    {
        int bit1;
        int bit3;
        int bit4;
    };

    // Instantiation
    struct value bit = {1, 2, 13};

    // Usage
    printf("%d, %d, %d\n", bit.bit1, bit.bit3, bit.bit4);

    // All done
    return 0;
}

Upvotes: 1

Sergey L.
Sergey L.

Reputation: 22542

What you are observing is sign-extended implicit integer conversion. When converting from a signed smaller integer type to a longer one the compiler will use sign-extended conversion. I.e. The leading bits will be filled with the most significant bit of the smaller type.

Your bitfield bit1 has only one bit. If you set it to 1 then the most significant bit is set and a sign extended conversion to int will lead to (int)0xFFFFFFFF == -1.

Same for bit4 which is 4 bit and initialised with 13 == 0xD This also has the most significant bit set. Extended to (int)0xFFFFFFFD == -3.

If you declare your bitfields as unsigned int then you will get zero-extended integer conversion and will observe the output

1, 2, 13

Upvotes: 3

Fiddling Bits
Fiddling Bits

Reputation: 8861

This will supply the values of the bitfields:

struct value
{
    unsigned int bit1:1;
    unsigned int bit3:4;
    unsigned int bit4:4;
}bit={1, 2, 13};

printf("%d, %d, %d\n", bit.bit1, bit.bit3, bit.bit4);

For getting the width of the bitfields, this is not possible...

Upvotes: 2

Related Questions