Thread: colon in the structure

  1. #1
    Samuel shiju's Avatar
    Join Date
    Dec 2003
    Posts
    41

    colon in the structure

    what is the use of colon in the structure.

    Code:
    int main ()
    {
    	struct {
    		int p:4;
    		int k:4;
    	}l;
    
    	l.p=10;
    	l.k=1000;
    
    	printf("%d\n",l.p);
    	printf("%d\n",l.k);
    	return 0;
    }
    
    output:
    -6
    -8

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Had to do some testing, but it appears to limit the number of bits used to repsent the number.

    As a test try this code out (adapted from the code you gave)
    Code:
    int main ()
    {
    struct {
    int p:3;
    int k:5;
    int a:2;
    }l;
    int c;
    for (c=0; c<20; ++c)
    {
      l.a=c;
      l.p=c;
      l.k=c;
      printf("%d\t%d\t%d\t%d\n",c,l.p,l.k,l.a);
    }
    return 0;
    }
    Did some more tests and here is what I've found. The struct will be allocated 4 bytes (32 bits) blocks for all the variables. So you could have 4 variables inside the struct that each only takes up 8 bits each and only use the orginal 4 byte block. However if you try to use 33 bits for all your variables then you will get another 4 byte block.

    So the following struct only takes 4 bytes
    Code:
      struct {
        int a:4;
        int b:4;
        int c:8;
        int d:8;
        char ch;
        }
    but the following takes 8 bytes
    Code:
      struct {
        int a:5;
        int b:4;
        int c:8;
        int d:8;
        char ch;
        }
    Last edited by Thantos; 12-11-2003 at 12:58 AM.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Just look up bit fields in any good C book
    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.

  4. #4
    Registered User Draco's Avatar
    Join Date
    Apr 2002
    Posts
    463
    good detective work thantos

  5. #5
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Think I should get a new book? Its only copyrighted 1987

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem referencing structure elements by pointer
    By trillianjedi in forum C Programming
    Replies: 19
    Last Post: 06-13-2008, 05:46 PM
  2. Replies: 5
    Last Post: 02-14-2006, 09:04 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Serial Communications in C
    By ExDigit in forum Windows Programming
    Replies: 7
    Last Post: 01-09-2002, 10:52 AM
  5. C structure within structure problem, need help
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 11-30-2001, 05:48 PM