C++11:variadic Macros (variable length parameter macro)

Source: Internet
Author: User
Tags variadic

Variadic Macros is function-like macros that contain a variable number of arguments.Remarks

To use Variadic macros, the ellipsis is specified as the final formal argument in a macro definition, and the Replacem ENT identifier __va_args__ May is used in the definition to insert the extra arguments. __va_args__ is replaced by all of the arguments that match the ellipsis, including commas between them.

The C standard specifies in least one argument must be passed to the ellipsis, to ensure that the macro does not Reso Lve to an expression with a trailing comma. The Visual C + + implementation would suppress a trailing comma if no arguments is passed to the ellipsis.

ExampleC++
Variadic_macros.cpp#include <stdio.h> #define Empty#define CHECK1 (x, ...) if (! ( x) {printf (__va_args__);} #define CHECK2 (x, ...) if ((x)) {printf (__va_args__);} #define CHECK3 (...) {printf (__va_args__);} #define MACRO (S, ...) printf (s, __va_args__) int main () {    CHECK1 (0, "Here%s%s", "is", "some", "varargs1 (1) \ n"); 
   check1 (1, "Here%s%s", "is", "some", "varargs1 (2) \ n");   Won ' t print    CHECK2 (0, "Here%s%s", "is", "some", "VARARGS2 (3) \ n");   Won ' t print    CHECK2 (1, "Here%s%s", "is", "some", "VARARGS2 (4) \ n");    Always invokes printf in the macro    CHECK3 ("Here%s%s", "is", "some", "VARARGS3 (5) \ n");    MACRO ("Hello, world\n");    MACRO ("error\n", EMPTY); Would cause error C2059, except VC + +/                              suppresses the trailing comma}
Output
Here is some varargs1 (1) Here is some varargs2 (4) Here is some varargs3 (5) Hello, worlderror

C++11:variadic Macros (variable length parameter macro)

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.