Apply for Zend Framework Certification Training

c




< Top 20 Questions of Predict output on file handling in c Variable Argument Lists with stdargh >



Bit Fields in C (Memory Optimization)

complete notes on Bit Fields- Using bit fields inside structures to save memory.Variable Argument Lists- Using <stdarg.h> to create functions that accept a variable number of arguments.

1. Bit Fields in C (Memory Optimization)
Definition
Bit fields allow you to allocate specific number of bits to structure members instead of full bytes (int = 4 bytes).
They are useful when memory is limited and values need only a few bits.
Syntax
struct structure_name {
    data_type variable_name : number_of_bits;
};
Example 1) Size Comparision
#include <stdio.h>
struct opStatusNormal{
    unsigned int power;
    unsigned int mode;
    unsigned int error;
};
struct opStatusBitFields{
    unsigned int power:1;//only 1 bits are allocated for it
    unsigned int mode:2;
    unsigned int error:1;
};
int main(){
    struct opStatusBitFields s;
    s.power=1;
    s.mode=2;
    s.error=0;
    printf("Power : %u \n",s.power);
    printf("Mode : %u \n",s.mode);
    printf("Error :%u \n",s.error);
    printf("Size of Normal Structure = %u bytes \n",sizeof(struct opStatusNormal));
    printf("Size of Bit Fields Structure = %u bytes \n",sizeof(struct opStatusBitFields));
    return 0;
}
Explanation
power : 1 → uses only 1 bit
mode  : 2 → uses 2 bits
error : 1 → uses 1 bit
Total = 4 bits instead of multiple bytes

Advantages
Saves memory
Useful in embedded systems
Efficient for flags and hardware registers

Limitations
Cannot take address (&) of bit field
Cannot use arrays of bit fields
Implementation-dependent (padding may occur)
Only integer types allowed
Practical Use Case
struct flags {
    unsigned int isLoggedIn : 1;
    unsigned int isAdmin    : 1;
    unsigned int isActive   : 1;

};
Used in:
Operating systems
Network protocols
Embedded devices

Example 2: Overflow in Bit Fields
#include <stdio.h>
struct Test {
    unsigned int x : 3;//only 3 bits are allocated for it 
};

int main() {
    struct Test t;
    t.x = 7;
    printf("%u\n", t.x);
    t.x = 8;
    printf("%u\n", t.x);
    return 0;

}
Output
7
0

Example 3: Hardware Register Style
#include <stdio.h>
struct ControlRegister {
    unsigned int enable : 1;
    unsigned int mode   : 2;
    unsigned int reset  : 1;
};

int main() {
    struct ControlRegister reg = {1, 2, 0};
    printf("Enable = %u\n", reg.enable);
    printf("Mode = %u\n", reg.mode);
    printf("Reset = %u\n", reg.reset);
    return 0;

}

 

< Top 20 Questions of Predict output on file handling in c Variable Argument Lists with stdargh >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top