View previous topic :: View next topic |
Author |
Message |
rikotech8
Joined: 10 Dec 2011 Posts: 376 Location: Sofiq,Bulgariq
|
syntax question. |
Posted: Fri May 25, 2012 2:58 am |
|
|
Hi everyone!
Excuse my bad English!
I am wondering what is the meaning of this type declaring variables?
What is :2 following the variable_name?
Thank you guys in advance! |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19535
|
|
Posted: Fri May 25, 2012 3:33 am |
|
|
Bitfield.
You can create smaller 'pieces' inside an integer, corresponding to particular bits. So as posted, creates an int8, in which you are only using the low two bits (value from 0 to 3). Normally you'd use it in something like a structure, so you can have one integer split into several parts with separate names for each.
Will be in a standard C reference book.
From K&R second edition:
Code: |
struct {
unsigned int is_keyword :1;
unsigned int is_extern :1;
unsigned int is_static :1;
} flags;
This defines a variable called flags, that contains three 1-bit field. The number following the colon represents the field width in bits. The fields declared unsigned int to ensure that they are unsigned quantities.
Individual fields are referenced in the same way as other structure members. (snipped)
Fields behave like small integers and may participate in arithmetic expressions just like other integers."
|
Also in the manual if you look in data definitions, it shows it, but doesn't do much to explain it:
Code: |
For example:
struct data_record {
int a [2];
int b : 2; /*2 bits */
int c : 3; /*3 bits*/
int d;
}data_var; // data_record is a structure type
|
Best Wishes |
|
|
rikotech8
Joined: 10 Dec 2011 Posts: 376 Location: Sofiq,Bulgariq
|
|
Posted: Fri May 25, 2012 4:49 am |
|
|
But there is something I don't understand.
Inside the structure, any member takes part of the 8-bit variable flag, but how could I know which one takes first bit, which one second bit and so on......
Also, can I declare variable (flag) bigger than 8 bit?
I hope you understand my question! |
|
|
jeremiah
Joined: 20 Jul 2010 Posts: 1353
|
|
Posted: Fri May 25, 2012 6:55 am |
|
|
This is all in the compiler manual.
The order of the fields determine which member is which bit.
You can do members larger than 8bits, but you do need to take care to not make certain members "cross" the byte boundary. Everything needs to align to the byte boundary.
Last edited by jeremiah on Sat May 26, 2012 9:43 am; edited 1 time in total |
|
|
rikotech8
Joined: 10 Dec 2011 Posts: 376 Location: Sofiq,Bulgariq
|
re |
Posted: Sat May 26, 2012 6:38 am |
|
|
Ok I see now.
Thank you! |
|
|
|