Hacker News new | ask | show | jobs
by PhilipRoman 465 days ago
You could probably restrict function pointer values with something like this:

    if(fptr == x || fptr == y)
        __builtin_unreachable()
Or...

    if(fptr != z && fptr != w)
        __builtin_unreachable()
But I'm not sure how well today's compilers can take advantage of this. You'd need a strict mode, where any function pointer is assumed to be the worst case. At that point might as well go for a real proof assistant
1 comments

A more practical way (short of explicit language support) would be to have an enum and a dispatcher function:

  enum { CALL_Z, CALL_W };
  int call_z_or_w(int which, int arg) {
    switch (which) {
      case CALL_Z: return z(arg);
      case CALL_W: return w(arg);
      default: __builtin_unreachable();
    }
  }
Or you could even do the same thing, but switching on the pointer value instead of an enum. Either way, this lets the compiler statically know where the call may possibly lead to.