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

That first example is terrible. C doesn't guarantee that the arguments to a macro are evaluated only once. At best, you might be doing the computation twice. At worst (if the function has internal state), you could get different answers for the comparison and the assignment. The non Haskell-style is better!


I also find the non-Haskell style much more readable, but I've spent a lot more time reading C code than Haskell code, so that could just be idiomatic familiarity. To me it's clearer that it's doing: "use this value, except that if it's below 0, clamp it to 0". The MAX() reads to me semantically strangely, since I tend to view "max" as idiomatic when selecting between values, like max(left_child,right_child), but not as an idiomatic way of clamping values. It works, of course, just takes me longer to unpack, the way using short-circuit booleans for control flow takes me a second to unpack.

If it's a case where you can retrieve the value essentially free w/o side effects (as opposed to the result of a computation), one idiomatic alternative is:

    const int a = foo >= 0 ? foo : 0;


Better to use the std::max template function.


Do note that calling functions with the unsafe side effects is not Haskell-style, as that expression is not even possible in Haskell without literally typing word "unsafe" into your program at least twice. It is supposedly "Haskell-style" only in the OP's incorrect description.




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

Search: