Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"#define" vs "#define 1"

The 1 seems unnecessary (and possibly misleading) in the following example, but I have seen this multiple times when used for checking #ifdefs:

#ifndef __NEWLIB_H__

#define __NEWLIB_H__ 1

Is there a difference or reason for using the above versus a plain #define __NEWLIB_H__?

like image 820
abc Avatar asked Jan 25 '23 06:01

abc


2 Answers

1 is true, so you can use the macro in an #if test. That's not usually very useful for header guards, but it certainly doesn't hurt. For other macros which might be tested in boolean expressions, the true value is definitely useful.

Some people just like the consistency. And that's the definition that gcc chooses by default if you put -D TESTME on the command line.

However,

#define __NEWLIB_H__ 1

is not cool unless it's in an implementation of the standard library, because names starting with two underscores (or an underscore and a capital letter) are reserved for use by the implementation, and should never be used in portable applications.

like image 106
rici Avatar answered Jan 27 '23 18:01

rici


When used purely as an #include guard, there is no difference between

#ifndef __NEWLIB_H__
#define __NEWLIB_H__

and

#ifndef __NEWLIB_H__
#define __NEWLIB_H__ 1

However, in general, there is a distinction.

Compiler error

#ifndef ABCD
#define ABCD
#endif

int main()
{
#if defined(ABCD) && (ABCD == 1)
   std::cout << "ABCD is 1\n";
#else
   std::cout << "ABCD is not 1\n";
#endif
}

Outputs the string "ABCD is 1"

#ifndef ABCD
#define ABCD 1
#endif

int main()
{
#if defined(ABCD) && (ABCD == 1)
   std::cout << "ABCD is 1\n";
#else
   std::cout << "ABCD is not 1\n";
#endif
}

Outputs the string "ABCD is not 1"

#ifndef ABCD
#define ABCD 10
#endif

int main()
{
#if defined(ABCD) && (ABCD == 1)
   std::cout << "ABCD is 1\n";
#else
   std::cout << "ABCD is not 1\n";
#endif
}
like image 25
R Sahu Avatar answered Jan 27 '23 20:01

R Sahu