Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meaning of ":" in struct C [duplicate]

Tags:

c

struct

Possible Duplicate:
What does 'unsigned temp:3' means

  struct Test
  {
      unsigned a : 5;
      unsigned b : 2;
      unsigned c : 1;
      unsigned d : 5;
  };

  Test B;
  printf("%u %u %u %u", B.a, B.b, B.c, B.d); // output: 0 0 0 0
  static struct   Test A = { 1, 2, 3, 4};

Could someone explain me what is purpose of : in struct, printf just outputs 0 so I assume these are not default values, but what they are then?

Also could someone explain me why does A.a, A.b, A.c, A.d outputs 1, 2, 1, 4 instead of 1, 2, 3, 4

like image 209
Dave Avatar asked Jun 25 '12 21:06

Dave


People also ask

What does struct * mean in C?

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.

What does in struct for C mean?

A struct in the C programming language (and many derivatives) is a composite data type (or record) declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the ...

How do I copy one struct to another?

A struct variable in Golang can be copied to another variable easily using the assignment statement(=). Any changes made to the second struct will not be reflected back to the first struct.

Can we copy struct in C?

We can also use assignment operator to make copy of struct. A lot of people don't even realize that they can copy a struct this way because one can't do same it with an array. Similarly one can return struct from a function and assign it but not array.


2 Answers

That is a bit field.

It basically tells the compiler that hey, this variable only needs to be x bits wide, so pack the rest of the fields in accordingly, OK?

like image 79
Richard J. Ross III Avatar answered Oct 28 '22 12:10

Richard J. Ross III


These are bit-fields see this Wikipeadia section on Bitfields or this reference about bit fields

The number after the : indicates how many bits you want to reserve for the identifier on the left. This allows you to allocate less space than ordinarily would be the case by tightly packing data. You can only do this in structs or unions.

Here is a short tutorial on bit-fields.

like image 34
Levon Avatar answered Oct 28 '22 10:10

Levon