Cool Code Snippet for Debugging

Revision en3, by beginner1010, 2020-04-16 03:57:01

Today, I was seeing tourist's submissions. He uses a very cool way to print the variables for the purpose of debugging. The function debug_out lists all variable names, followed by their values. I found it very interesting and convenient.

However, when you would like to print a long list of variables, it might be hard to match variables and their corresponding values. I made a few changes, and I would like to share the code with you. Please note that you need to define XOX (-D XOX should do the job). Therefore, when you are submitting your code, you do not need to remove or comment out lines including debug. Hope you'll find it useful.

#include <bits/stdc++.h>
using namespace std;
vector<string> vec_splitter(string s) {
	s += ',';
	vector<string> res;
	while(!s.empty()) {
		res.push_back(s.substr(0, s.find(',')));
		s = s.substr(s.find(',') + 1);
	}
	return res;
}
void debug_out(
vector<string> __attribute__ ((unused)) args,
__attribute__ ((unused)) int idx, 
__attribute__ ((unused)) int LINE_NUM) { cerr << endl; } 
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
	if(idx > 0) cerr << ", "; else cerr << "Line(" << LINE_NUM << ") ";
	stringstream ss; ss << H;
	cerr << args[idx] << " = " << ss.str();
	debug_out(args, idx + 1, LINE_NUM, T...);
}
#ifdef XOX
#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)
#else
#define debug(...) 42
#endif
int main() {
	int x = -1, y = 10000;
	double z = 0.2;
	string s = "beginner1010";
	long long b = 1LL << 60;
	
	debug(x, y, z, s, b);
	
	double aux = 1010.0;
	string code = "code";
	
	debug(code + "forces",-aux / 10 * 2.3);
	return 0;
}

Results:

Line(34) x = -1,  y = 10000,  z = 0.2,  s = beginner1010,  b = 1152921504606846976
Line(39) code + "forces" = codeforces, -aux / 10 * 2.3 = -232.3

UPD 1: The code is further improved to handle the case when an operation is applied to variables in debug. The line number is added, and spookywooky's suggestion is applied. Please see the examples. Thank you all for your suggestions.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English beginner1010 2020-04-16 03:57:01 764 Tiny change: ' operation. The line' -> ' operation in `debug`. The line'
en2 English beginner1010 2020-04-15 21:35:57 9
en1 English beginner1010 2020-04-15 21:31:46 1664 Initial revision (published)