What makes a better constant in C, a macro or an enum?

后端 未结 6 1160
栀梦
栀梦 2020-12-02 13:32

I am confused about when to use macros or enums. Both can be used as constants, but what is the difference between them and what is the advantage of either one? Is it someho

6条回答
  •  爱一瞬间的悲伤
    2020-12-02 14:05

    As a practical matter, there is little difference. They are equally usable as constants in your programs. Some may prefer one or the other for stylistic reasons, but I can't think of any technical reason to prefer one over the other.

    One difference is that macros allow you to control the integral type of related constants. But an enum will use an int.

    #define X 100L
    enum { Y = 100L };
    
    printf("%ld\n", X);
    printf("%d\n", Y); /* Y has int type */
    

提交回复
热议问题