Блог пользователя diego_v1

Автор diego_v1, 10 лет назад, По-английски

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!

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
10 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

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 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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 лет назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

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 лет назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

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 лет назад, # |
Rev. 2   Проголосовать: нравится -33 Проголосовать: не нравится

WTF going with typing

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

Is it too difficult ?