Is #defining within a block really a code smell?

  • A+
Category:Languages

I read that #defining and #undefining inside a block is a code smell. Why is that? Also, I see that in the code(just a sample that shows what I have in the actual code), this compiles,

if(x == 1000) {     #define MACRO_EXAMPLE 1 } else {     #define MACRO_EXAMPLE 1 } 

But this does not compile,

if(x == 1000) {     #define MACRO_EXAMPLE 1 } else {     #define MACRO_EXAMPLE 2 } 

with the error warning C4005: 'MACRO_EXAMPLE' : macro redefinition

How does this get preprocessed? How does it work?


preprocessing happens before your code is analyed. This means that the if/else is ignored and

if(x == 1000) {     #define MACRO_EXAMPLE 1 } else {     #define MACRO_EXAMPLE 1 } 

is actualy treated as

#define MACRO_EXAMPLE 1 #define MACRO_EXAMPLE 1 

which is okay because you use the same value. On the other hand

if(x == 1000) {     #define MACRO_EXAMPLE 1 } else {     #define MACRO_EXAMPLE 2 } 

becomes

#define MACRO_EXAMPLE 1 #define MACRO_EXAMPLE 2 

and since the value of the macro has changed it is an error

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: