Avatar ·

Why do C++ macros use meaningless do-while and if-else?

Hello! I started learning C++ and came across a strange pattern in macros. I often see such constructs in library code (for example, in Qt or Boost): ```cpp #define LOG_ERROR(msg) do { \ std::cerr << "ERROR: " << msg << std::endl; \ } while(0) ``` Or: ```cpp #define SAFE_DELETE(p) if(p) { delete p; p = nullptr; } else (void)0 ``` At first glance, this looks completely meaningless. Why write `do { ... } while(0)` if the loop executes exactly once? And why not just write: ```cpp #define LOG_ERROR(msg) std::cerr << "ERROR: " << msg << std::endl ``` I tried using a simple macro without do-while, and it worked in a simple case. But then I inserted it into an if-else condition, and the code broke. For example: ```cpp #define LOG_ERROR(msg) std::cerr << ```