Learnings from Redis # 1 / Macros

Harkrishn Patro
2 min readMar 27, 2021

--

I‘ve been going through Redis (Redis is an OSS in-memory database) code base and I can definitely say this is one of the most well written code for maintainability over the years. I’m not a systems programmer so I find few of the nuances interesting and thought of sharing it with others.

Redis Logo
if (0) {

Have you ever seen such coding pattern in C/C++? The very first thought that would come into one’s mind is, this would never get executed then why? I stumbled upon this and was also struck by the same question. And then after a bit of diving deep through the code base, I finally realised what’s going on here. The idea of the programmer/author is to support multiple else if block and in order to reduce the duplicate code, macros are defined for the else if block. Here how it goes in the Redis code base:

if (0) { config_set_special_field("requirepass") {// Some coding logic...} config_set_special_field("save") {// Some coding logic...}

If you don’t look at it carefully, the assumption would be that none of these methods below would ever get executed however config_set_special_field is a macro. Let’s take a look at the macro.

#define config_set_special_field(_name) \    } else if (!strcasecmp(c->argv[2]->ptr,_name)) {

This macro basically is an else if block which compares if two strings are equal. Now let’s process the above code and visualize how it would look once the macros are replaced.

if (0) {// Nothing happens in this block.} else if (!strcasecmp(c->argv[2]->ptr, "requirepass")) {// Some coding logic...} else if (!strcasecmp(c->argv[2]->ptr, "save")) {// Some coding logic...}

As you can see now, the macros have been replaced and the first if block remains empty and following else if block are the one which will get executed/evaluated.

The above code is from the config.c file in Redis and over there, there are multiple such conditional checks hence the author (Salvatore Sanfilippo aka antirez) has opted to use a macro. I would also suggest to use the pattern only if the number of such checks are a lot and is repetitive and can be replaced with a macro.

In the next story I will talk about the interesting String library (sds) used in Redis. Do share if you have some interesting anecdote.

Follow me to learn such interesting coding patterns and tricks.

--

--