Debugging in C++

Правка en2, от del_acc, 2019-02-25 14:17:57

cerr

You can use cerr instead of cout to debug. cerr writes to the standard error stream which is not seen by the online judge.

Example:

instead of cout << "x is " << x << '\n';

you can use cerr << "x is " << x << '\n';

One drawback of this is that cerr increase the runtime of a program. The runtime of the below program would decrease if the cerr statements were removed.

for(int i = 0; i<n; i++)
{
    for(int j = 0; j<n; j++)
    {
        cout << i*j << "\n";
        cerr << "i is " << i << "\n"
        cerr << "j is " << j << "\n"
    }
}

We are facing a trade-off between coding time and running time.

When our solution seems good, we should remove some debugging statements which consume some time.

Watch Macro

This macro is an easy way to debug variables. It also prints the name of the variable:

#define watch(x) cerr << "\n" << (#x) << " is " << (x) << endl

You can use it like this:

#include<bits/stdc++.h>
using namespace std;

#define watch(x) cerr << "\n" << (#x) << " is " << (x) << endl;

int main()
{
    int n;
    n = 2*2;
    watch(n); //output : n is 4
    int exponent = 2;
    watch(pow(n,exponent)); //output: pow(n,exponent) is 16
}

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en4 Английский del_acc 2019-02-25 18:56:10 163
en3 Английский del_acc 2019-02-25 14:21:26 364
en2 Английский del_acc 2019-02-25 14:17:57 20
en1 Английский del_acc 2019-02-25 14:17:24 1282 Initial revision (published)