-3

Consider following code

#include<stdio.h>
#include<conio.h>

struct mystruct
{
    int a:1;
    int b:2;
    int c:3;
};

void main()
{
    struct mystruct S;
    clrscr();
    S.a=1;
    S.b=-5;
    S.c=100;
    printf("%d %u %d %u %d %u",S.a,S.a,S.b,S.b,S.c,S.c);
    getch();
}
Martin
  • 3,703
  • 2
  • 21
  • 43
  • 7
    You forgot to ask a question. – Eregrith Sep 27 '12 at 07:47
  • i am new and dont know how to ask a question in stackoverflow..... i wanted to ask the beahviou of bit fields but now i know the answer thanks. – Shankar Bhatnagar Sep 27 '12 at 07:56
  • 1
    @ShankarBhatnagar Surprisingly, it works just the same way as when you ask questions to other people in the real world. – Lundin Sep 27 '12 at 07:58
  • 1
    `void main()` is wrong; it should be `int main(void)`. If your textbook told you to use `void main()`, please find a better one. – Keith Thompson Sep 27 '12 at 08:10
  • @Lundin i meant that i put my question based on this code in the 'title' part. See top to find the question. – Shankar Bhatnagar Sep 27 '12 at 11:50
  • @KeithThompson [Not necessarily](http://stackoverflow.com/questions/5296163/why-is-the-type-of-the-main-function-in-c-and-c-left-to-the-user-to-define/5296593#5296593) although in this particular case, it is quite certain that we are dealing with a hosted application, so you are correct. – Lundin Sep 27 '12 at 11:52
  • @Eregrith: find the question at the top , in the TITLE (above the advertisement) :) – Shankar Bhatnagar Sep 27 '12 at 11:52

2 Answers2

2

You're defining a 1-bit signed number a. That doesn't make a lot of sense, since there's no bits left for anything once the sign has been encoded. Small bitfields should typically be of an unsigned type, and fields of width 1 must be, then you can store 0 or 1 which is probably what you meant.

The same problem happens with the b member, it's only two bits wide but you're trying to store -5, which really doesn't encode in two bits very easily.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • i already got my answer by running and repeatedly modifying my code. thanks! :) – Shankar Bhatnagar Sep 27 '12 at 07:54
  • "You're defining a 1-bit signed number `a`" -- Not necessarily. The signedness of a bit field declared as `int` is implementation-defined. Use `signed int` if you want a signed bit field, or `unsigned int` if you want an unsigned bit field (which is almost always what you want). – Keith Thompson Sep 27 '12 at 08:10
0

Statements S.b = -5 and S.c = 100 will cause an overflow (since you are assigning values that cannot be held in 2 or 3 bits), and hence S.b and S.c won't contain the value you expect them to.

Raj
  • 4,342
  • 9
  • 40
  • 45