Debug in C++

Revision en7, by zenny0212, 2025-11-23 17:11:40

Tired of typing cout more than actual logic? Try this macro. It lets you debug anything (just override << first).

Works for almost every C++ type. Side effects may include cleaner code and sudden confidence in debugging.

//*** debug(x) ***//
#define DEBUG 1

#if DEBUG
#define del cout << '\n'
#define debug(...) _debug(#__VA_ARGS__, __VA_ARGS__)
template <class X, class Y>
ostream& operator<<(ostream& os, pair<X, Y> const& p) {
    return os << "(" << p.first << ", " << p.second << ")";
}
template <class Ch, class Tr, class Container>
basic_ostream<Ch, Tr>& operator<<(basic_ostream<Ch, Tr>& os, Container const& x) {
    int i = 0, n = (int)distance(x.begin(), x.end());
    os << "{ ";
    for (const auto& y : x) os << y << (++i < n ? ", " : "");
    return os << " }";
}
template <typename... Args>
void _debug(const char* s, Args&&... args) {
    cout << "{ ";
    size_t i = 0, cnt = 0, n = sizeof...(args);
    auto next = [&]() {
        while (s[i] && (s[i] == ' ' || s[i] == ',')) ++i;
        size_t st = i;
        while (s[i] && s[i] != ',') ++i;
        return string(s + st, i - st);
    };
    auto dummy = {(cout << next() << ": " << args << (++cnt < n ? ", " : ""), 0)...};
    (void)dummy;
    cout << " }" << '\n';
}
#else
#define del
#define debug(...)
#endif
Full debug code
Output of full debug code

Drop a comment if you agree—or if you’ve got a genius idea you’re hiding!

Update: It works with C++11 or newer C++ versions

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en7 English zenny0212 2025-11-23 17:11:40 53 Tiny change: ' hiding!\n' -> ' hiding!\n\nUpdate: It works with C++11 or newer C++ versions\n'
en6 English zenny0212 2025-11-23 17:09:58 214
en5 English zenny0212 2025-05-30 09:53:26 12
en4 English zenny0212 2025-05-30 05:52:02 3168
en3 English zenny0212 2025-05-28 18:30:39 3
en2 English zenny0212 2025-05-28 18:28:41 0 (published)
en1 English zenny0212 2025-05-28 18:28:12 7023 Initial revision (saved to drafts)