Hi,
consider the snippet:
#include <stdio.h>
#define DUMMY 100
#define FOO 200
#define DUMMY 200
int main (void)
{
printf("%d, %d\n",FOO, DUMMY);
return 0;
}
The compiler I'm using (gcc-4.1.2) emits warning message about redefined
macro, but picks up and prints the last defined, i.e. with value 200. Is
this platform dependent behavior, or undefined behavior?
6.103p2 says:
An identifier currently defined as an object-like macro shall not be redefined by another
#define preprocessing directive unless the second definition is an object-like macro
definition and the two replacement lists are identical. ...
Both #defines of DUMMY define it as an object-like macro, but the
replacement lists are not identical. This "shall" occurs in a
Constraints section, so a diagnostic is required. The warning message
meets that requirement.
A conforming implementation of C is allowed, but not required, to accept
the code after issuing the diagnostic. If the code is accepted, the
behavior of the program when executed is not defined by the C standard.
gcc-4.1.2 apparently has chosen one of the two most obvious ways of
dealing with this situation: letting the the second value override the
first. The other most obvious way is to keep the value as 100. Either
option is permitted, as well as many other options that could be much
nastier. I do NOT recommend relying upon this behavior.
The following two alternatives don't violate that constraint, and have
behavior corresponding to the two "obvious ways" I mentioned above:
Option 1:
#ifdef DUMMY
#undef DUMMY
#endif
#define DUMMY 200
Option 2:
#ifndef DUMMY
#define DUMMY 200
#endif