10

I am trying to print out to console using a macro the variable name for display members value while debugging ( logging ). How to do that? I tried the following but it doesnt' work.

#define MY_PRINT(x) std::cout << "'x'=" << x << std::endl;

int main(){
   int my_variable=3;
   MY_PRINT( my_variable );
   // I would like to print to console
   // 'my_variable'=3
}
Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
Abruzzo Forte e Gentile
  • 14,423
  • 28
  • 99
  • 173

2 Answers2

25

Auch... I found the solution.

I should write the macro like this

 #define MY_PRINT(x) std::cout << #x"=" << x << std::endl
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Abruzzo Forte e Gentile
  • 14,423
  • 28
  • 99
  • 173
5

For C++ I use this:

#define STR(x) #x << '=' << x

int main()
{
  int i = 1;
  std::string str("hello");
  std::vector<std::string> vec;
  my_class mc;

  ...

  std::cout << STR(i) << std::endl
            << STR(str) << std::endl
            << STR(vec) << std::endl
            << STR(mc) << std::endl;

  return 0;
}

This way the compiler chooses the streaming operator based on the data type, so you don't need to bother with different macros for each, and it can go to any std::ostream, not just std::cout. Just provide the appropriate streaming operator for your data:

std::ostream operator<<(std::ostream&, const T&);
std::ostream operator<<(std::ostream&, const std::vector<T>&);
etc

But I wish there was a template way to replace the macro, or at least the variable name provided by the #x.

shodanho
  • 51
  • 1
  • 3