Jin Jin - 3 months ago 6
C Question

Confusion about redefining constant using define directive(#define) in C

As far as I know, standard allows redefinition only if the new definition duplicates the old one. So for example,

If,

#define X 100


Then,

#define X 200 // Not allowed
#define X 100 // Allowed


But what confuses me is when the header file includes redefintion which doesn't duplicate the old defintion. For example,

There is a header file,
header.h
such that

#ifndef X
#define X 100
#endif


and source code
main.c
such that

#define X 10
#include "header.h"


Since
#define X 100
is below
#define X 10
in the
main
file, I thought this would occur error. But surprisingly, the compiler does not complain! Why is such behaviour allowed in C?

Answer

Of course it doesn't, because #define X 100 is never reached.

Think about this, what does #ifndef do?

Put the #define X 10 below the #include, what happens now?