pranay.agra's blog

By pranay.agra, history, 4 years ago, In English

I am quite new to C++, and I am currently trying to add an appropriate template. I see that most of the good coders have some type of debugging statement such as the following:

void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef PRANAY_DEBUG
#define dbg(...) cerr << "(" << #__AA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif

int main() {
ios_base::sync_with_stdio(0);
#ifndef PRANAY_DEBUG
    cin.tie(nullptr);
#endif
}

However, I am not sure how to use this. If I write dbg(a, b) and run my program, I do not see any additional print statements in the terminal. I believe that this is because I am not passing the flag correctly, but I am not really sure what this means and/or how to best do this for a CP set-up. I have tried running g++ -PRANAY_DEBUG a.cpp as some have suggested, but I get an unrecognized command line option error.

  • Vote: I like it
  • +6
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it +9 Vote: I do not like it

g++ -DPRANAY_DEBUG a.cpp

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Works, thanks! Another quick question: What is the point of the 4 lines of code in my main method? The flag above seems to work without it.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Here is an SO explaining the reasoning behind those lines. http://stackoverflow.com/questions/31162367/significance-of-ios-basesync-with-stdiofalse-cin-tienull

      The #ifndef makes sure you only remove the tie between cin and cout once you submit, which in particular means locally output will be flushed each time before inputting. I don't think putting cin.tie(0); inside a #ifndef is necessary.

      `

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      sync_with_stdio => I am not gonna use C I/O (scanf, printf, fgets, etc), so I do not need backward compatibility. This ensures C++ I/O (cout, cin) are as efficient as possible.

      cin.tie => Syscalls are expensive. Write is one of them. So, when you use cout, the output is buffered, that is, collected together to be printed in a batch. The standard behaviour of C++ is to flush cout when a cin comes, which makes sense because if you ask to enter a name (for eg), you want that the user sees the prompt. However, in CP we don't care about this (except in interactive problems, where you need to comment this out) so we remove this "tied stream".

      Also note that you shouldn't use endl. It flushes the cout buffer. Use \n instead.