amc amc - 2 months ago 20
C Question

Peculiar use of C macros

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?

Answer

These constants used to just be #defines, 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 #defines, 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.