diego_v1's blog

By diego_v1, 10 years ago, In English

Recently, there has been a couple of blog entries about macros to trace/debug variables in C++. I found them quite interesting, but none is actually what I'm looking for. I'm not very familiar with templates (I actually never used them), so maybe what I'm about to ask isn't even possible.

I'd like to have a macro/template/anything in my program that allows me to do something like this...

int A[2];
for(int i = 0; i < 2; i++) A[i] = i;
for(int i = 0; i < 2; i++) trace(A[i]);

And I'd like to receive this as output...

A[0] = 0
A[1] = 1
A[2] = 2

When using the macros posted in the previous entries by other coders, I get this...

A[i] = 0
A[i] = 1
A[i] = 2

Is it possible to actually get the array name and index when using tracing/debugging macros with arrays?

I'd like to receive any kind of help/information on the matter. Thanks in advance!

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
10 years ago, # |
  Vote: I like it +3 Vote: I do not like it

I don't think it's possible. Every macro is replaced by its content in compile time. The preprocessor wouldn't even know the value of i.

»
10 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I don't think it's possible too, but you may use smth like

trace(i, A[i]) to get i = 1, A[i] = 1

»
10 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

Try following code

#include <cstdio>

#define debug(a, i) printf(#a "[%d] = %d\n", i, a[i]);

int main() {
    int A[100];
    for (int i = 0; i < 10; i++) {
        debug(A, i);
    }
}
»
10 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

It's possible! =) But with some restrictions.

struct Counter{
	static int k;
	Counter(){ k++; }
	~Counter() { k--; }
};
int Counter::k = 0;
#define LOL(x) {string s = #x; Counter c##x; cout<<s.substr(0,1+s.find('['))<<Counter::k<<"]="<<x<<'\n'; }
  • »
    »
    10 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Awesome!

    I implemented it in my template. Thanks a lot!

»
10 years ago, # |
Rev. 2   Vote: I like it -33 Vote: I do not like it

WTF going with typing

cout << "A[" << i << "] " << A[i] << endl;

Is it too difficult ?