Peculiar use of C macros

c, constants, enums, preprocessor

Solution

These constants used to just be `#define`s, so what you're seeing is probably there to protect you from accidentally mixing old and new header files. An advantage of using `enum` to define the constants is that `enum` members tend to be available in the debugger, and `#define` macros don't.

If you were to (accidentally) include some other header file that also tries to `#define SOCK_STREAM`, you would get a compiler warning instead of silently using a possibly incorrect value.

UPDATE

Looking through a glibc git repo, I found the specific commit that added the `#define`s, with this comment:

* sysdeps/generic/socketbits.h: Also make SOCK_* constants available
as macros so that #ifdef works.
* sysdeps/unix/sysv/linux/socketbits.h: Likewise.

There you have it.

Problem

Reading the code of the C library's sockets interface, I found this: ``` /* Types of sockets. */ enum __socket_type { SOCK_STREAM = 1, /* Sequenced, reliable, connection-based byte streams. */ #define SOCK_STREAM SOCK_STREAM SOCK_DGRAM = 2, /* Connectionless, unreliable datagrams of fixed maximum length. */ #define SOCK_DGRAM SOCK_DGRAM ... ``` This "idiom" is used all over bits/socket.h. I am just curious, what is the purpose of those macros?

Original source