You need to know how scopes work in C++. If you have a variable in one scope (between { }
), this variable will be destroyed at the end of its scope.
void main()
{ // scope of function main()
int x;
{ // new scope
int y;
} // y gets destroyed here
} // x gets destroyed here
The body of an if
statement is a scope, too. Even if you don't have curly brackets but only a single statement like this:
if (true) // new scope
int z;
// end of this scope
A variable can only be used in the scope it is declared in, or in any nested scope. This means I could still use x
from the first code snippet in new scope where y
is declared, but I can't access y
from the outer scope.
When I understand your intention correct, you want something similar to this:
#include <fstream>
#define DEBUG_LEVEL 1
int main() {
#if DEBUG_LEVEL == 1
std::ofstream output_file("outputDelta.txt"); // create output file
#endif
for (int i = 0; i < 1e2; i++) {
#if DEBUG_LEVEL == 1
output_file << i << "\n";
#endif
}
return 0;
}
Note that the DEBUG_LEVEL
now is not a variable but a macro. The preprocessor will check the conditions of your #if
s and either keep the code in between if they evaluate to true, or remove it if not. Therefore all the "removed" code won't be compiled.
When you set DEBUG_LEVEL
to something else, it would be as if you just had commented out the lines between each #if DEBUG_LEVEL == 1
and #endif
.
As @Ayxan Haqverdili pointed out, writing all these #if
s and #endif
s will polute your code and make it harder to read and understand.
If you want a better alternative, there are many loggers available online, but if you want to create your own, it's not that hard (to create a simple one).
I had something like this in a game of mine:
#if DEBUG_LEVEL == 1
#define DEBUG_LOG(msg) Log::Error(msg, __FILE__, __LINE__) // some logging function
#else
#define DEBUG_LOG(msg)
#endif
This is just a minimal example but I had something like this. Since the preprocessor will only define the DEBUG_LOG(msg)
to be substituted by my logging function when DEBUG_LEVEL
is 1
, the logging function will only be called then, and if the DEBUG_LEVEL
is 0
, then it's going to do nothing at all.