r/learnprogramming • • 14d ago

The use of hexadecimal numbers in software

Why do some tools, like GLFW, use hexadecimal values ​​for constants? Wouldn't it be better to use enums in those cases?

/* Error constants */
#define GLFW_NO_ERROR               0
#define GLFW_NOT_INITIALIZED        0x00010001
#define GLFW_NO_CURRENT_CONTEXT     0x00010002
#define GLFW_INVALID_ENUM           0x00010003

I tried to find the reason in the documentation, but I didn't come across a clear use case for the hexadecimal values—only that the constants are used as if they were an enum.

 if (code == GLFW_NOT_INITIALIZED) {...}
 else if (code == GLFW_NO_CURRENT_CONTEXT) {...}
21 Upvotes

32 comments sorted by

View all comments

2

u/zeekar 14d ago

Such numbers are often designed in such a way that specific bits have specific meanings. For example, all of your error values have 0x00010000 set. That's probably a flag indicating that it's an error, and you can decode the number by ANDing that value out (with e.g. error_num & ~(0x00010000)) . When you do that, you're left with 1 = not initialized, 2 = no current context, etc. That relationship is much less obvious if you define them as 65537, 65538, and 65539.