C++26: A User-Friednly assert() macro

https://news.ycombinator.com/rss Hits: 9
Summary

C++26 is bringing some long-overdue changes to assert(). But why are those changes needed? And when do we actually use assert, anyway?At its core, assert() exists to validate runtime conditions. If the given expression evaluates to false, the program aborts. I’m almost certain you’ve used it before — at work, in personal projects, or at the very least in examples and code snippets.So what’s the problem?The macro nobody treats like a macroassert() is a macro — and a slightly sneaky one at that. Its name is written in lowercase, so it doesn’t follow the usual SCREAMING_SNAKE_CASE convention we associate with macros. There’s a good chance you’ve been using it for years without ever thinking about its macro nature.Macros, of course, aren’t particularly popular among modern C++ developers. But the issue here isn’t the usual - but valid - “macros are evil” argument. The real problem is more specific:The preprocessor only understands parentheses for grouping. It does not understand other C++ syntax such as template angle brackets or brace-initialization.As a result, several otherwise perfectly valid-looking assertions fail to compile:1 2 3 4 5 6 7 // https://godbolt.org/z/9sqM7PvWh using Int = int; int x = 1, y = 2; assert(std::is_same<int, Int>::value); assert([x, y]() { return x < y; }() == 1); assert(std::vector<int>{1, 2, 3}.size() == 3); Each of these breaks for essentially the same reason: the macro argument parsing gets confused by commas or braces that aren’t wrapped in an extra pair of parentheses.You can fix each of them, of course, by adding an extra pair of parentheses. For example the last assertion would become assert((std::vector<int>{1, 2, 3}.size() == 3)); - you can play with the examples here.But let’s be honest: this is ugly, easy to forget, and not exactly beginner-friendly. Sure, after hitting the problem once or twice, most people internalize the workaround — just like with the most vexing parse. Still, it’s unnecessary friction for such a fundamental...

First seen: 2026-03-28 15:41

Last seen: 2026-03-29 00:45