Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define IDENTIFIER without a token

Tags:

c

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?

like image 581
Fahad Anwar Avatar asked Aug 06 '13 07:08

Fahad Anwar


3 Answers

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
like image 123
Nerius Avatar answered Oct 20 '22 00:10

Nerius


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
like image 10
iabdalkader Avatar answered Oct 20 '22 02:10

iabdalkader


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.

like image 8
torek Avatar answered Oct 20 '22 00:10

torek