What are C macros useful for?

前端 未结 18 2125
-上瘾入骨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:16

    I end up having to remember what the macro is and substitute it in my head as I read.

    That seems to reflect poorly on the naming of the macros. I would assume you wouldn't have to emulate the preprocessor if it were a log_function_entry() macro.

    The ones that I have encountered that were intuitive and easy to understand were always like little mini functions, so I always wondered why they weren't just functions.

    Usually they should be, unless they need to operate on generic parameters.

    #define max(a,b) ((a)<(b)?(b):(a))
    

    will work on any type with an < operator.

    More that just functions, macros let you perform operations using the symbols in the source file. That means you can create a new variable name, or reference the source file and line number the macro is on.

    In C99, macros also allow you to call variadic functions such as printf

    #define log_message(guard,format,...) \
       if (guard) printf("%s:%d: " format "\n", __FILE__, __LINE__,__VA_ARGS_);
    
    log_message( foo == 7, "x %d", x)
    

    In which the format works like printf. If the guard is true, it outputs the message along with the file and line number that printed the message. If it was a function call, it would not know the file and line you called it from, and using a vaprintf would be a bit more work.

提交回复
热议问题