“static const” vs “#define” vs “enum”

后端 未结 17 1496
一生所求
一生所求 2020-11-21 05:45

Which one is better to use among the below statements in C?

static const int var = 5;

or

#define var 5

o

17条回答
  •  梦如初夏
    2020-11-21 06:07

    Another drawback of const in C is that you can't use the value in initializing another const.

    static int const NUMBER_OF_FINGERS_PER_HAND = 5;
    static int const NUMBER_OF_HANDS = 2;
    
    // initializer element is not constant, this does not work.
    static int const NUMBER_OF_FINGERS = NUMBER_OF_FINGERS_PER_HAND 
                                         * NUMBER_OF_HANDS;
    

    Even this does not work with a const since the compiler does not see it as a constant:

    static uint8_t const ARRAY_SIZE = 16;
    static int8_t const lookup_table[ARRAY_SIZE] = {
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // ARRAY_SIZE not a constant!
    

    I'd be happy to use typed const in these cases, otherwise...

提交回复
热议问题