Jin Jin - 6 months ago 21
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,


#define X 100


#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,
such that

#ifndef X
#define X 100

and source code
such that

#define X 10
#include "header.h"

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


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?