Skip to main content

Kill min/max macros!

Kill min/max macros!

I guess by now we all know that macros suck. Nevertheless, sometimes you just have to work with them unknowingly, i.e. if a library does spooky stuff like this:

#ifndef max
#define max(a,b)  (((a) < (b)) ? (b) : (a))
#ifndef min
#define min(a,b)  (((a) < (b)) ? (a) : (b))

For my thesis, I'm working with an embedded system. Now, there exists the concept of unaddressed data, namely 'streams'. A library simulation of a stream that is functionally equivalent looks like this:

template<typename T>
struct stream
    std::deque<T> data;
    void write(T v) { data.push_back(v); }
    T read()        { auto tmp = data.front(); data.pop_back(); return tmp; }

    bool empty() const { return data.empty(); }

Guess what: It is really, really bad to read() inside of those 'nice' macros min/max. The following snippets may quickly yield a segmentation fault, depending on the amount of data present in the stream.

int maximum = 0;
    maximum = max(maximum,;

Just something we need to be aware of. :-(