11/03/2008

struct的特別用法

#include 

typedef struct A {
    int up : 1;
    int down : 1;
    int left : 1;
    int right : 1;
}Cell;

int main(void) {
    Cell c;

    c.up = c.down = c.left = c.right = 0;
    c.down = 1;
    printf("%d %d\n", sizeof(Cell), sizeof c);
    printf("%d %d %d %d\n", c.up & 1, c.down & 1, c.left & 1, c.right & 1);
    printf("%d %d %d %d\n", c.up, c.down, c.left, c.right);
    return 0;
}
結果:
4 4
0 1 0 0
0 -1 0 0

宣告的變數會變成bit-field struct因padding大小是4個byte.
裡面的變數都是bit 只能做bit operator 否則結果不是你想要的.

沒有留言: