Why are C macros not type-safe?

后端 未结 7 1773
礼貌的吻别
礼貌的吻别 2021-02-18 16:01

If have encountered this claim multiple times and can\'t figure out what it is supposed to mean. Since the resulting code is compiled using a regular C compiler it will end up b

7条回答
  •  后悔当初
    2021-02-18 16:18

    Macros aren't type safe because they don't understand types.

    You can't tell a macro to only take integers. The preprocessor recognises a macro usage and it replaces one sequence of tokens (the macro with its arguments) with another set of tokens. This is a powerful facility if used correctly, but it's easy to use incorrectly.

    With a function you can define a function void f(int, int) and the compiler will flag if you try to use the return value of f or pass it strings.

    With a macro - no chance. The only checks that get made are it is given the correct number of arguments. then it replaces the tokens appropriately and passes onto the compiler.

    #define F(A, B)
    

    will allow you to call F(1, 2), or F("A", 2) or F(1, (2, 3, 4)) or ...

    You might get an error from the compiler, or you might not, if something within the macro requires some sort of type safety. But that's not down to the preprocessor.

    You can get some very odd results when passing strings to macros that expect numbers, as the chances are you'll end up using string addresses as numbers without a squeak from the compiler.

提交回复
热议问题