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

后端 未结 17 1447
一生所求
一生所求 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:22

    The definition

    const int const_value = 5;
    

    does not always define a constant value. Some compilers (for example tcc 0.9.26) just allocate memory identified with the name "const_value". Using the identifier "const_value" you can not modify this memory. But you still could modify the memory using another identifier:

    const int const_value = 5;
    int *mutable_value = (int*) &const_value;
    *mutable_value = 3;
    printf("%i", const_value); // The output may be 5 or 3, depending on the compiler.
    

    This means the definition

    #define CONST_VALUE 5
    

    is the only way to define a constant value which can not be modified by any means.

提交回复
热议问题