amc amc - 5 months ago 60
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. */
SOCK_DGRAM = 2, /* Connectionless, unreliable datagrams
of fixed maximum length. */

This "idiom" is used all over bits/socket.h. I am just curious, what is the purpose of those macros?


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.


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.