Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of saying "#define FOO FOO" in C?

I came across some C code where the author uses the following idiom all over the place:

typedef __int32 FOO_INT32;
#define FOO_INT32 FOO_INT32

What is the point of doing this? Shouldn't the typedef be enough? It is a workaround for some wonky C compilers out there?

like image 260
cwick Avatar asked Mar 11 '09 22:03

cwick


2 Answers

With the #define instruction, you'll then be able to test if the typedef has been done somewhere else in the code using :

#ifdef FOO_INT32
FOO_INT32 myfoo;
#else
int myfoo;
#endif
like image 181
claf Avatar answered Sep 26 '22 09:09

claf


It's a practice that's sometimes done in headers. The #define allows for compile-time testing of the existence of the typedef. This allows code like:

#ifdef FOO_INT32
FOO_INT32 myfoo;
#else
int myfoo;
#endif

or as a true guard #define, similar to header file guards.

#ifndef FOO_INT32
typedef int FOO_INT32
#define FOO_INT32 FOO_INT32
#endif

It's not necessarily a good practice, but it has its uses, especially when you have some headers which use types defined by other libraries, but you want to provide your own substitutes for cases when you're not using those libraries at all.

like image 39
SPWorley Avatar answered Sep 26 '22 09:09

SPWorley