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

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

    A simple difference:

    At pre-processing time, the constant is replaced with its value. So you could not apply the dereference operator to a define, but you can apply the dereference operator to a variable.

    As you would suppose, define is faster that static const.

    For example, having:

    #define mymax 100
    

    you can not do printf("address of constant is %p",&mymax);.

    But having

    const int mymax_var=100
    

    you can do printf("address of constant is %p",&mymax_var);.

    To be more clear, the define is replaced by its value at the pre-processing stage, so we do not have any variable stored in the program. We have just the code from the text segment of the program where the define was used.

    However, for static const we have a variable that is allocated somewhere. For gcc, static const are allocated in the text segment of the program.

    Above, I wanted to tell about the reference operator so replace dereference with reference.

提交回复
热议问题