|
|
|
|
|
by orangeduck
4384 days ago
|
|
Macros in C can sometimes be nasty, but "min" is a pathological case for a macro because it isn't what macros were meant for. In reality "min" should just be a function, and you should write a separate function for each type you want to define it over. This is how this problem is solved in C, and almost all other languages. It just looks deceptive because C's native operators like "<" and ">" happen to be generic across some number types. This is just for convenience, it isn't how C is meant to be programmed. Pretty much every other language also makes you define different implementations of functions when you have a different type you want it to work on. Lots let you type the same function name, independent of the type - via generics, interfaces, or type-classes - but all call out to different implementations at the end of the day. Very few can derive those implementations. As far as I am concerned, Macros in C are best used just to save on typing. They get a lot of hate because the syntax looks like functions - so people try to use them as functions. I don't recommend using them as functions, instead use them to save typing - because saving typing and avoiding repeating yourself can only reduce errors. |
|
Tell that to Kernighan and Ritchie. The second macro in K&R (I googled a PDF of the second edition) is
Yes, that's lowercase 'max', and they even mention "This macro will work for any data type; there is no need for different kinds of max for different data types, as there would be with functions"Macros certainly were intended for this, as it was the only way to guarantee that the compiler inlined code (probably the only way it ever inlined function calls)
And for the curious: the first macro they give is
That certainly is what macros were meant for :-), and doesn't even save on typing.But yes, in modern C, nobody would use a macro for this.