In my code, i have lots of couts which i use for debugging purposes. Rather than having to comment out all the cout statements, i've heard there is a much easier way to get the compiler to ignore any cout statements it comes across by using things such as #ifdef........ however, i really don't know how to implement this.
Let's take a really simple program:
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
float x, y;
x = 5.3;
y = x * x;
cout << "x^2 = " << y << endl;
return 0;
}
so how would i implement the #ifdef thing (if indeed you can) on to something such as this?
Then you would write your cout line like this: Debug("x^2 = " << y << endl);
If the macro USEDEBUG is defined, this will resolve to: std::cout << "x^2 = " << y << endl;
and otherwise, it will just disappear, since Debug(x) will be defined to to nothing.
//includes
#include "stdafx.h"
#include <iostream>
#include <vector>
//function prototypes
int outputVec( vector v );
//Debug
#define USEDEBUG
#ifdef USEDEBUG
#define Debug( x ) std::cout << x
#else
#define Debug( x )
#endif
//typedef
typedef std::vector< int > vector;
typedef std::vector< int >::iterator iterator;
int _tmain(int argc, _TCHAR* argv[])
{
Debug( "Debug is on.\n" );
vector v;
for( int i = 0; i < 10; ++i )
v.push_back( i + 2 );
Debug( outputVec( v ) );
return 0;
}
int outputVec( vector v )
{
iterator iter = v.begin();
while( iter != v.end() )
{
std::cout << *iter << '\n';
++iter;
}
return 1;
}
I tried this with: void outputVec( vector v )
But with this, I am unable to compile. So by using int as a return value, it compiles and runs fine, only I print out the return value along with the vector.
So this: Debug( outputVec( v ) );
caused an error when 'outputVec' is a void function? This is because 'outputVec' doesn't return a value, so 'outputVec(v)' has no value to be send to std::cout.
Or do I have to actually define these at compile time?
While debugging this and making dbug = true. Stepping into the if statement on line 41, the only line that gets executed is line 45. Lines 43 and 44 are skipped.