Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> int a = f();

> if (a < 0) a = 0;

> has been replaced with

> const int a = MAX(0,f());

Going by MAX capitalization, it must be a macro, in which case the code is wrong. I am guessing this is a synthetic example, but still - try and get the basics right.



With GCC specifics, you can define MAX as a macro without calling the function twice.

  #define max(a,b) \
        ({ typeof (a) _a = (a); \
        typeof (b) _b = (b); \
        _a > _b ? _a : _b; })


Technically, the code is wrong only if f() is not pure.


Yes, I know, but there is no way to enforce it. This a classic "noob" mistake with macros - using a macro argument more than once.


That's why in C++ people seem to generally recommend inline functions instead. Not only do the arguments only get evaluated once, but the whole thing is type safe too.

Of course, people still misuse macros.


Macros, by definition, are always misused, complete the languages point of view. They exist to let the programmer get the job done when the language falls short.


Well, I would define misuse as using them when the language doesn't fall short, like for the max example.


I feel pretty safe assuming a pure function in a blog post about the advantages of immutability, really.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: