What are C macros useful for?

前端 未结 18 2034
-上瘾入骨i
-上瘾入骨i 2020-11-28 19:45

I have written a little bit of C, and I can read it well enough to get a general idea of what it is doing, but every time I have encountered a macro it has thrown me complet

18条回答
  •  失恋的感觉
    2020-11-28 20:22

    From Computer Stupidities:

    I've seen this code excerpt in a lot of freeware gaming programs for UNIX:

    /*
    * Bit values.
    */
    #define BIT_0 1
    #define BIT_1 2
    #define BIT_2 4
    #define BIT_3 8
    #define BIT_4 16
    #define BIT_5 32
    #define BIT_6 64
    #define BIT_7 128
    #define BIT_8 256
    #define BIT_9 512
    #define BIT_10 1024
    #define BIT_11 2048
    #define BIT_12 4096
    #define BIT_13 8192
    #define BIT_14 16384
    #define BIT_15 32768
    #define BIT_16 65536
    #define BIT_17 131072
    #define BIT_18 262144
    #define BIT_19 524288
    #define BIT_20 1048576
    #define BIT_21 2097152
    #define BIT_22 4194304
    #define BIT_23 8388608
    #define BIT_24 16777216
    #define BIT_25 33554432
    #define BIT_26 67108864
    #define BIT_27 134217728
    #define BIT_28 268435456
    #define BIT_29 536870912
    #define BIT_30 1073741824
    #define BIT_31 2147483648

    A much easier way of achieving this is:

    #define BIT_0 0x00000001
    #define BIT_1 0x00000002
    #define BIT_2 0x00000004
    #define BIT_3 0x00000008
    #define BIT_4 0x00000010
    ...
    #define BIT_28 0x10000000
    #define BIT_29 0x20000000
    #define BIT_30 0x40000000
    #define BIT_31 0x80000000

    An easier way still is to let the compiler do the calculations:

    #define BIT_0 (1)
    #define BIT_1 (1 << 1)
    #define BIT_2 (1 << 2)
    #define BIT_3 (1 << 3)
    #define BIT_4 (1 << 4)
    ...
    #define BIT_28 (1 << 28)
    #define BIT_29 (1 << 29)
    #define BIT_30 (1 << 30)
    #define BIT_31 (1 << 31)

    But why go to all the trouble of defining 32 constants? The C language also has parameterized macros. All you really need is:

    #define BIT(x) (1 << (x))

    Anyway, I wonder if guy who wrote the original code used a calculator or just computed it all out on paper.

    That's just one possible use of Macros.

提交回复
热议问题