Macro definition of variable parameters

Source: Internet
Author: User

Parameters of the output functions printf () and fprintf () are variable. When debugging a program, you may want to define your own variable output functions,

The Variable Parameter macro is an option.

The macro in c99 can have variable parameters like a function, such

#define LOG(format, ...) fprintf(stdout, format, __VA_ARGS__)

Where,... indicates that the parameter is variable, __va_args _ is replaced by the actual parameter set in preprocessing.

 

GCC also supports the following forms

#define LOG(format, args...) fprintf(stdout, format, args)

The usage is basically the same as the above, but the parameter symbols have changed.

 

Note that variable parameters cannot be omitted in the macro definition. Although you can pass an empty parameter, it is necessary to mention the usage of the "#" Concatenation symbol.

"##" Is used to connect token. In the preceding example, format, _ va_args _, and ARGs are token,

If the token is empty, no connection is made. Therefore, variable parameters (_ va_args _ and ARGs) can be omitted. Modify the variable macro as follows:

#define LOG(format, ...)     fprintf(stdout, format, ##__VA_ARGS__)
#define LOG(format, args...) fprintf(stdout, format, ##args)

 

The preceding Variable Parameter macro definition can not only customize the output format, but also works with # ifdef # else # endif for convenient output management,

For example, the debugging information is output during debugging, but not during official release.

#ifdef DEBUG
#define LOG(format, ...) fprintf(stdout, ">> "format"\n", ##__VA_ARGS__)
#else
#define LOG(format, ...)
#endif

In the debugging environment, log macro is a variable parameter output macro that is output in a custom format;

In the release environment, log macro is an empty macro and does nothing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.