Question

What is the purpose of using #define to define a constant with no value?

Such as:

#define TOKEN

Was it helpful?

Solution

You can use it to enable or disable certain code using #ifdef or #ifndef, eg this:

#ifdef TOKEN
    printf("token is defined");
#endif

One use for this would be to toggle logging in debug builds. Another would be include guards.

OTHER TIPS

As @Nutomic says, this sort of #define is useful for enabling/disabling certain bits of code. I've seen this used to create compile-time options for a given library:

#ifdef STRICT_PARSING
  //...
#endif

#ifdef APPROXIMATE_PARSING
  //...
#endif

#ifdef UNICODE //this is especially useful when trying to control Unicode vs ANSI builds
  //call Unicode functions here
#else
  //call Ansi functions here
#endif

#ifdef USE_STL //another good one, used to activate or deactivate STL-based bits of an API; the function declarations were dependent on USE_STL being defined. A plain-C API was exposed either way, but the STL support was nice too.
  std::string MyApi();
#endif
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top