Jin Jin - 1 year ago 66
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?

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download