Why are C macros not type-safe?

后端 未结 7 1749
礼貌的吻别
礼貌的吻别 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:26

    Consider the typical "max" macro, versus function:

    #define MAX(a,b) a < b ? a : b
    int max(int a, int b) {return a < b ? a : b;}
    

    Here's what people mean when they say the macro is not type-safe in the way the function is:

    If a caller of the function writes

    char *foo = max("abc","def");
    

    the compiler will warn.

    Whereas, if a caller of the macro writes:

    char *foo = MAX("abc", "def");
    

    the preprocessor will replace that with:

    char *foo = "abc" < "def" ? "abc" : "def";
    

    which will compile with no problems, but almost certainly not give the result you wanted.

    Additionally of course the side effects are different, consider the function case:

    int x = 1, y = 2;
    int a = max(x++,y++); 
    

    the max() function will operate on the original values of x and y and the post-increments will take effect after the function returns.

    In the macro case:

    int x = 1, y = 2;
    int b = MAX(x++,y++);
    

    that second line is preprocessed to give:

    int b = x++ < y++ ? x++ : y++;
    

    Again, no compiler warnings or errors but will not be the behaviour you expected.

提交回复
热议问题