Flags, enum (C)

后端 未结 6 1489
既然无缘
既然无缘 2021-02-02 14:54

I\'m not very used to programming with flags, but I think I just found a situation where they\'d be useful:

I\'ve got a couple of objects that register themselves as lis

6条回答
  •  日久生厌
    2021-02-02 15:42

    another way of storing flags is to not bother with the underlying type at all. when using an enum, the enum values are stored by default into an unsigned int, which is 32 bits on a common computer. this gives you with only 32 possible flags: while certainly much, there are some cases where it is not sufficient.

    now you can define your flag set this way:

    typedef struct
    {
        int takes_damage : 1;
        int grabbable    : 1;
        int liquid       : 1;
        int some_other   : 1;
    } flags;
    

    if you never encountered this, the ': 1' part tells the compiler to only use 1 bit to store this struct member.

    now you can define a variable to hold the flags, and work with those flags:

    flags myflags = {1,0,0,1}; // defines a variable holding a set of flags, with an initial value of takes_damage & some_other
    
    myflags.liquid = 1; // change the flags to include the liquid
    
    if ( myflags.takes_damage ) // test for one flag
        apply_damage();
    if ( myflags.liquid && myflags.some_other ) // test for multiple flags
        show_strange_behavior();
    

    this method allows you to define any number of flags, without limitation, and you can extend your flag set at any time without fearing an overflow. the drawback is that testing a subset of the flags is more cumbersome and necessitate more code.

提交回复
热议问题