Thread: question about bit fields?

  1. #1
    Registered User
    Join Date
    Oct 2015
    Posts
    11

    Exclamation question about bit fields?

    when i watch a video about bit fileds to understand it
    the teacher who made the video he wrote this:
    Code:
      struct
      {
      int member : 3;
      }d1;
      d1.member=7;
    and he said that: d1.member is can stored 7(cause you specify 3bits to use it )and he run the program and the out put was 7 it works normally.
    the problem when i copy his program in my compiler code blocks
    i surprised because the out put was -8 and it's different from the first ...i creat some program to understand what happning and finally i found that out :
    when we write this
    Code:
      struct 
      {
       int member : 3;
      //it means we use just 2 bits for store the number and last one is     for sign(negative or positive number).
       }d1;
    so the greatest value we can store it in d1.member is 3 not 7.

    where's the right ?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You are correct - there is a sign bit even for bit-field integers.

    so int member : 3; has range -4 to 3.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    The signedness of bit fields is implementation-defined. That is, a compiler could treat it as either signed or unsigned--yours treats it as signed whereas the compiler that the teacher in the video used treats it as unsigned. Either way is acceptable according to the standards.

    Use an explicit "signed" or "unsigned" type modifier if the signedness matters to you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Bit fields and hex
    By MeNeedsHelp in forum C Programming
    Replies: 22
    Last Post: 09-27-2014, 03:44 AM
  2. Bit fields
    By Edelweiss in forum C Programming
    Replies: 5
    Last Post: 08-23-2011, 10:01 AM
  3. Bit fields
    By Perspektyva in forum C++ Programming
    Replies: 13
    Last Post: 11-22-2008, 02:38 PM
  4. bit fields before non-bit fields . . .
    By dwks in forum C Programming
    Replies: 10
    Last Post: 10-13-2005, 02:36 AM
  5. Struct Fields Question
    By Beast() in forum C Programming
    Replies: 9
    Last Post: 12-16-2004, 07:00 AM

Tags for this Thread