0

I used to do this CPP, to debug my code quickly.

code.cpp:

#define bug(x) cout << #x << ": " << x << '\n'

int main() {
    int a = 5;
    bug(a);

    int b = 3;
    bug(b);
    
    return 0;
}

output:

a: 5
b: 3

what this does is, it print the variable name along with it's value dynamically.

now I am trying to make something like this in dart, but couldn't find anything.

can such thing be even done in dart ?? btw, if you a better debug practice, please let me know :)

I searched on StackOverflow, but couldn't find anything:

  • Get Variables name by it's value in Dart Lang:
    • the answer mentioned only prints the value from a map, but what I am asking is to print the variable name itself (a, b) along their value (5, 3)
    • and using reflectable prints the variable name by passing value, but I simply want to print variable name by passing variable itself.

I even asked ChatGPT, but this is what it came up with:

void bug(var x) {
  print('$x: ${x.toString()}');
}

void main() {
  int x = 5;
  bug(x);
}

not useful at all :facepalm:, as this will print 5: 5.

samyak039
  • 42
  • 6
  • @MendelG, the approach mentioned it this answer is a manual approach, I have to maintain the list of variables by myself. which will become a bit tedious. – samyak039 Jan 04 '23 at 06:07
  • 2
    ChatGPT literally has no idea what it's talking about. As a source for facts, it's less trustworthy than a random web search. – molbdnilo Jan 04 '23 at 07:09
  • 2
    Don't rely on printing debug output, it will change the behavior (timing) of your code. Instead write unit tests and use a debugger to find your problems. (In other words you don't want your debug code to be different from your release code) – Pepijn Kramer Jan 04 '23 at 07:19
  • 1
    This is not possible without metaprogramming (such as by using a preprocessor or by using code generation). – jamesdlin Jan 04 '23 at 08:34
  • @molbdnilo, exactly. but I like to test it's limit, so for those problems which I am unable to find answer on the web, I turn to ChatGPT. always fascinated by what it comes up with. – samyak039 Jan 04 '23 at 10:03
  • @PepijnKramer okay, understood your point. will change my habit. thanks mate :) – samyak039 Jan 04 '23 at 10:04
  • @jamesdlin I see, then I'll leave it, and try to apply what said. – samyak039 Jan 04 '23 at 10:05

0 Answers0