Hacker News new | ask | show | jobs
by rwmj 2025 days ago
Missing the most important case: Some external library you need changes a function signature and you need to be able to compile against the old or the new library, eg:

  #if LIBVERSION >= 2
    draw_point (2, 3, RED);
  #else
    set_color (RED);
    draw_point (2, 3);
  #endif
This is actually a case where the C preprocessor would be useful in many more languages. OCaml has cppo which is like a better cpp and is very useful for solving these sorts of problems. (https://github.com/ocaml-community/cppo)
1 comments

You can use "if constexpr" for that.
In this case this doesn't work because "if constexpr" parses both branches. If the new library version changes function signatures, the if-branch for the old library version produces an error:

https://www.godbolt.org/z/4KK997

PS: interesting to note that Zig does the "right thing":

https://www.godbolt.org/z/9c13PY

There was a proposal to do the correct thing and copy D's static if, but it was rejected for fairly contrived reasons IIRC.

Andrei Alexandrescu mentions it in a talk, if constexpr doesn't really do much of anything useful because it introduces a scope.

Even though one or other branch of the if-statement won't be valid C++? How does it know that set_color is a function if it isn't defined anywhere?