Is #define banned in industry standards?

前端 未结 13 2839
长发绾君心
长发绾君心 2020-12-23 18:52

I am a first year computer science student and my professor said #define is banned in the industry standards along with #if, #ifdef, <

13条回答
  •  情深已故
    2020-12-23 19:28

    Some coding standards may discourage or even forbid the use of #define to create function-like macros that take arguments, like

    #define SQR(x) ((x)*(x))
    

    because a) such macros are not type-safe, and b) somebody will inevitably write SQR(x++), which is bad juju.

    Some standards may discourage or ban the use of #ifdefs for conditional compilation. For example, the following code uses conditional compilation to properly print out a size_t value. For C99 and later, you use the %zu conversion specifier; for C89 and earlier, you use %lu and cast the value to unsigned long:

    #if __STDC_VERSION__ >= 199901L
    #  define SIZE_T_CAST
    #  define SIZE_T_FMT "%zu"
    #else
    #  define SIZE_T_CAST (unsigned long)
    #  define SIZE_T_FMT "%lu"
    #endif
    ...
    printf( "sizeof foo = " SIZE_T_FMT "\n", SIZE_T_CAST sizeof foo );
    

    Some standards may mandate that instead of doing this, you implement the module twice, once for C89 and earlier, once for C99 and later:

    /* C89 version */
    printf( "sizeof foo = %lu\n", (unsigned long) sizeof foo );
    
    /* C99 version */
    printf( "sizeof foo = %zu\n", sizeof foo );
    

    and then let Make (or Ant, or whatever build tool you're using) deal with compiling and linking the correct version. For this example that would be ridiculous overkill, but I've seen code that was an untraceable rat's nest of #ifdefs that should have had that conditional code factored out into separate files.

    However, I am not aware of any company or industry group that has banned the use of preprocessor statements outright.

提交回复
热议问题