Why are preprocessor macros evil and what are the alternatives?

前端 未结 8 2035
面向向阳花
面向向阳花 2020-11-22 02:46

I have always asked this but I have never received a really good answer; I think that almost any programmer before even writing the first \"Hello World\" had encountered a p

8条回答
  •  心在旅途
    2020-11-22 03:00

    A common trouble is this :

    #define DIV(a,b) a / b
    
    printf("25 / (3+2) = %d", DIV(25,3+2));
    

    It will print 10, not 5, because the preprocessor will expand it this way:

    printf("25 / (3+2) = %d", 25 / 3 + 2);
    

    This version is safer:

    #define DIV(a,b) (a) / (b)
    

提交回复
热议问题