3

I have the following C code.

struct values{ int a:3; int b:3; int c:2; }; void main(){ struct values v={2,-6,5}; printf("%d %d %d",v.a,v.b,v.c); } 

When I execute the code, I am getting the following output:

2 2 1. 

But output should be 2 -6 5, right?

If I'm wrong please explain.

2
  • 4
    Are you familiar with the bit fields? (:3 etc) Commented Sep 1, 2013 at 15:35
  • 1
    The Clang compiler on OS X gives me a nice warning: "implicit truncation from 'int' to bitfield changes value from -6 to 2 [-Wconstant-conversion]". Commented Sep 1, 2013 at 15:53

3 Answers 3

5

-6 exceeds the range of a 3-bit signed int. Therefore you're observing an artifact of undefined implementation-defined behaviour (in practice, the most-significant bits of your value are being thrown away).

Sign up to request clarification or add additional context in comments.

1 Comment

yes but implementation defined behavior (c99, 6.3.1.3p3) not undefined
4
{2, | -6, | 5 } 010 last 3 bits | 010 last 3 bits | 01 last 2 bits 2 2 1 

2 Comments

Consider elaborating a little on this answer.
@P0W Was simply looking through the answers and was in no mood to vote but could not resist after looking at your explanation ..... brief but explains everything except if one understands something .. +1 :) and for others too :P
1

No. Output is 2 2 1.

The C compiler converts the values to Binary, and stores in the memory.

Binary value of 2 : 00000010

Binary value of -6: 11111010 (11111001+1)

Binary value of 5 : 00000101

While storing in memory:

For 2, 010 will be stored.

For -6, 010 will be stored.

For 5, 01 will be stored.

When you access these variables from your main method, for v.a "010" will be returned, here left most bit is for sign.

So v.a is 2. Similarly v.b is 2 and v.c is 1.

Hope it helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.