4

In a header file in.h one can see this pattern:

enum {
  IPPROTO_IP = 0,               /* Dummy protocol for TCP               */
#define IPPROTO_IP              IPPROTO_IP
  IPPROTO_ICMP = 1,             /* Internet Control Message Protocol    */
#define IPPROTO_ICMP            IPPROTO_ICMP

What the reason for redefinition of already defined symbol? If I understand correctly, when preprocessor encounter IPPROTO_ICMP, it will replace it with IPPROTO_ICMP, so nothing will change.

Stas Bushuev
  • 318
  • 3
  • 9
  • 1
    Yes, it's a duplicate, but not knowing the answer, I'd never considered that enum is important and so not found them. – Stas Bushuev Jul 01 '16 at 08:38

2 Answers2

3

One common, useful use of self-reference is to create a macro which expands to itself. If you write

#define EPERM EPERM

then the macro EPERM expands to EPERM. Effectively, it is left alone by the preprocessor whenever it's used in running text. You can tell that it's a macro with #ifdef. You might do this if you want to define numeric constants with an enum, but have #ifdef be true for each constant.

Reference : http://gcc.gnu.org/onlinedocs/gcc-4.6.2/cpp/Self_002dReferential-Macros.html#Self_002dReferential-Macros

Twinkle
  • 514
  • 3
  • 8
2

As I understand it's hack for use enumeration in C preprocessor directives! If you try to compile this code - you will get an error:

enum {
    VAL_0 = 0,
    VAL_1,
};
#if (!defined(VAL_0))
#   error "VAL_0 not defined!"
#endif

But! In this case, no error will generated:

enum {
    VAL_0 = 0,
#   define VAL_0    VAL_0
    VAL_1,
#   define VAL_1    VAL_1
};
#if (!defined(VAL_0))
#   error "VAL_0 not defined!"
#endif

EDIT:

And as wrote Twinkle it is just define itself without value that have enumeration members. So this preprocessor construction will get error:

#if (VAL_1 != 1)
#   error "VAL_1 just defined and have default value 0"
#endif
imbearr
  • 999
  • 7
  • 22