Eli
Eli

Reputation: 53

How to write a function to replace #ifdef and #endif pair?

I use #ifdef and #endif a lot in my code, for example:

#include<iostream>
#define __TEST____
int main()
{
    std::cout<<"do something 1"<<std::endl;
#ifdef __TEST____

         // a 
         // lot
         // of 
         // test codes
#endif
    return 0;
}

The #ifdef and #endif pairs reduces code readability. How to write a function to replace the #ifdef and #endif pairs ? Just like this one:


#include<iostream>
#define __TEST____
#define TEST(...) { #ifdef __TEST____ {__VA_ARGS__} #endif}
int main()
{
    std::cout<<"do something 1"<<std::endl;
    TEST(
         // a 
         // lot
         // of 
         // test codes
         );
    return 0;
}

Upvotes: 3

Views: 454

Answers (1)

LoPiTaL
LoPiTaL

Reputation: 2605

In C++ (any version) you could just change the order of the #ifdef and the #define:

#ifdef __TEST__
# define TEST(...) { __VA_ARGS__ }
#else
# define TEST(...)
#endif

int main()
{
    std::cout<<"do something 1"<<std::endl;
    TEST(
         // a 
         // lot
         // of 
         // test codes
         );
    return 0;
}

Upvotes: 3

Related Questions