Token = = invalid in preprocessor expressions

I have a program:

#include <iostream> #define _DEBUG = 1 using namespace std; int main() { #if (_DEBUG == 1) cout << "hello : " <<endl; #endif return 0; } 

When compiling, this gives an error:

 $ g++ a.cpp a.cpp:7:7: error: token "=" is not valid in preprocessor expressions $ g++ --version g++ (MacPorts gcc46 4.6.3_8) 4.6.3 

I thought == is a conditional equality operator?

+4
source share
3 answers

Just a typo, I think:

 #define _DEBUG = 1 

it should be

 #define _DEBUG 1 

I do it all the time!

+8
source
 #define _DEBUG = 1 

Declares _DEBUG as a macro that expands to = 1 , so when it expands in a conditional expression, you get

 #if (= 1 == 1) 

which is clearly not a valid conditional expression. You need to remove = from the macro definition:

 #define _DEBUG 1 

In addition, for flag macros like this, it is usually recommended to check if a macro is defined, and not a macro value. For instance,

 #ifdef _DEBUG 
+8
source

It should be

 #define textToBeReplaced ReplacementText 

The compiler will execute all your code and replace all instances of textToBeReplaced with replaceText.

In your case it will be

 #define _debug 1 


Once again notice that your

  #if(_debug==1) 

should be

  #ifdef _debug 

Please note that 1 never comes into play here? that means you can really just do

  #define _debug 

and do not install it on anything

+3
source

Source: https://habr.com/ru/post/1436036/


All Articles