Last active
December 15, 2019 22:05
-
-
Save mogenson/f0a7d14885834064baed093faa940a19 to your computer and use it in GitHub Desktop.
Example: default value for optional macro argument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Copyright (c) 2019 Michael Mogenson | |
* MIT license https://opensource.org/licenses/MIT | |
*/ | |
/* This contrived example demonstrates the use of the comma operator and | |
* variadic arguments to create a function-like macro that accepts an optional | |
* argument and provides a default value when no argument is supplied. | |
* | |
* C's comma operator will evaluate the statement to the left of the comma and | |
* return the value of the statement to the right. The line `if (i++, true)` is | |
* equivalent to `i++; if (true)`. | |
* | |
* The C preprocessor macro __VA_ARGS__ will expand to the arguments (if any) | |
* passed to a function-like macro. The __VA_OPT__() macro will insert the | |
* content between the parenthesis only if __VA_ARGS__ is not empty. | |
* | |
* This BREAK() macro will break out of a loop if a supplied conditional | |
* evaluates to true. If no argument is provided, a default true value is used. | |
*/ | |
#include <stdio.h> | |
#define BREAK(...) if (1 __VA_OPT__(,) __VA_ARGS__) break | |
int main() { | |
while (1) { | |
printf("break immediately\n"); | |
BREAK(); // => if (1) break; | |
} | |
for (int i = 0; i < 5; i++) { | |
printf("i = %d\n", i); | |
BREAK(i > 3); // => if (1, i > 3) break; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment