In C, the size of union or struct members can be stated in bits. Bit fields allow users to manage memory efficiently by letting them explicitly declare a data member in bits. Allowable data types for a bit field include qualified and unqualified signed int, and unsigned int.
Note, the sizeof() operator will not work on bit fields.
struct label {
datatype var : no_of_bits;
};
#include<stdio.h>
struct fan {
//Remember length is in bits. 8 bit = 1 byte
unsigned int no_of_blades : 3;
unsigned int speed : 3;
unsigned int price : 16;
};
int main(void)
{
struct fan table_fan;
table_fan.no_of_blades = 3;
table_fan.speed = 4;
table_fan.price = 1000;
printf("sizeof table_fan = %d bytes\n", sizeof(table_fan));
printf("table_fan.no_of_blades = %u\n",table_fan.no_of_blades);
printf("table_fan.speed = %u\n",table_fan.speed);
printf("table_fan.price = %u\n",table_fan.price);
return 0;
}
sizeof table_fan = 4 bytes
table_fan.no_of_blades = 3
table_fan.speed = 4
table_fan.price = 1000
Bit fields with a length of 0 must be unnamed. Unnamed bit fields cannot be referenced or initialized. A zero-width bit-field aligns the next field to the boundary (by padding bits) defined by the datatype of the bit-field.
#include<stdio.h>
struct A {
int var1 : 2;
int var2 : 6;
};
struct B {
int var1 : 2;
int : 0;
int var2 : 6;
};
int main()
{
struct A a;
struct B b;
printf("sizeof a = %d\n", sizeof(a));
printf("sizeof b = %d\n", sizeof(b));
return 0;
}
sizeof a = 4
sizeof b = 8
C Programming
Overview Hello World Installation Comments Header Files Data Types Tokens Operators Input/Output Format Specifiers Decision Control Loops Type Qualifiers Storage class specifier Arrays Enums Structures Unions Functions Recursions Inline Functions Pointers Pointer Arithematic Call by value and call by reference Linked Lists Passing of Arrays in Functions Preprocessor and Macros Mathematical Operations String Operations Bit Fields Command Line Arguments Variable Arguments Error Handling Type Casting Typedef File Handling Multi Processing Threads Outdated C Programming Memory Management Compilation C Programs Interview Questions MiscellaneousTrending
C Programming
Remember to follow community guidelines and don't go off topic.