Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

__VA_OPT__

Use case

Clean variadic macros without trailing comma issues.

Explanation

__VA_OPT__(,) inserts comma only when __VA_ARGS__ is non-empty.

Code

#include <cstdint>
#include <format>
#include <iostream>

#define LOG(fmt, ...)                                                          \
  std::cout << std::format(fmt __VA_OPT__(, ) __VA_ARGS__) << "\n"

int main() {
  // Without __VA_OPT__(,), this:
  // std::cout << std::format(fmt, __VA_ARGS__) << "\n"
  // would expand to:
  // std::cout << std::format("Analysis started.", ) << "\n"
  // causing an error.
  LOG("Analysis started.");
  LOG("Found branch at {:#x}", 0x1000);
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/va-opt
Analysis started.
Found branch at 0x1000