Fahad Anwar
Fahad Anwar

Reputation: 349

#define IDENTIFIER without a token

What does the following statement mean:

#define FAHAD

I am familiar with the statements like:

#define FAHAD 1

But what does the #define statement without a token signify? Is it that it is similar to a constant definition?

Upvotes: 34

Views: 9818

Answers (4)

Amit009
Amit009

Reputation: 51

#define FAHAD

this will act like a compiler flag, under which some code can be done. this will instruct the compiler to compile the code present under this compiler option

#ifdef FAHAD
printf();
#else
/* NA */
#endif

Upvotes: 2

iabdalkader
iabdalkader

Reputation: 17332

it means that FAHAD is defined, you can later check if it's defined or not with:

#ifdef FAHAD
  //do something
#else
  //something else
#endif

Or:

#ifndef FAHAD //if not defined
//do something
#endif

A real life example use is to check if a function or a header is available for your platform, usually a build system will define macros to indicate that some functions or headers exist before actually compiling, for example this checks if signal.h is available:

#ifdef HAVE_SIGNAL_H
#   include <signal.h>
#endif/*HAVE_SIGNAL_H*/

This checks if some function is available

#ifdef HAVE_SOME_FUNCTION
//use this function
#else
//else use another one
#endif

Upvotes: 10

torek
torek

Reputation: 489488

Any #define results in replacing the original identifier with the replacement tokens. If there are no replacement tokens, the replacement is empty:

#define DEF_A "some stuff"
#define DEF_B 42
#define DEF_C
printf("%s is %d\n", DEF_A, DEF_B DEF_C);

expands to:

printf("%s is %d\n", "some stuff", 42 );

I put a space between 42 and ) to indicate the "nothing" that DEF_C expanded-to, but in terms of the language at least, the output of the preprocessor is merely a stream of tokens. (Actual compilers generally let you see the preprocessor output. Whether there will be any white-space here depends on the actual preprocessor. For GNU cpp, there is one.)

As in the other answers so far, you can use #ifdef to test whether an identifier has been #defined. You can also write:

#if defined(DEF_C)

for instance. These tests are positive (i.e., the identifier is defined) even if the expansion is empty.

Upvotes: 9

Nerius
Nerius

Reputation: 980

Defining a constant without a value acts as a flag to the preprocessor, and can be used like so:

#define MY_FLAG
#ifdef MY_FLAG
/* If we defined MY_FLAG, we want this to be compiled */
#else
/* We did not define MY_FLAG, we want this to be compiled instead */
#endif

Upvotes: 28

Related Questions