Thread: bit modifier in structure

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    16

    bit modifier in structure

    Hello Everyone,

    Somewhere on web, I got this code example of structure (I don't remember but it was something like the snippet below):

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    typedef struct str
    {
    unsigned int first:1;
    int second:1;
    
    
    }str;
    
    
    int main()
    {
        str exp;
        exp.first=1;
        exp.second=1;
    
    
        printf("%d %d\n", exp.first,exp.second);
    
    
    
    
        exp.first=-1;
        exp.second=-1;
    
        printf("%d %d\n", exp.first,exp.second);
    
        return 0;
    }
    Both the printf prints
    1 -1
    Could you please explain why. This may look because of "signed"(as it is obvious) but I failed to get any explanation for why "exp.second" prints "-1" at first print statement !!

    Thanks in advance
    Last edited by shaswat; 05-24-2019 at 07:51 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,415
    A 1-bit unsigned int can only ever be 0 or 1.
    A 1-bit signed int can only ever be 0 or -1 (the single bit IS the sign bit).
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. volatile modifier
    By veera in forum C Programming
    Replies: 4
    Last Post: 08-12-2012, 01:59 AM
  2. const modifier
    By Vertex34 in forum C Programming
    Replies: 8
    Last Post: 09-27-2004, 07:22 PM
  3. DNS & Mail settings modifier
    By DemonSoul in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 05-20-2004, 12:43 PM
  4. Clipboard Modifier
    By Korhedron in forum Windows Programming
    Replies: 2
    Last Post: 01-03-2004, 02:32 PM

Tags for this Thread