I need to write a macro which traps any invalid index i for an array of length n. Here is what I got so far:
#define TRAP(i, n) (((unsigned int) (i) < (n))? (i): (abort(), 0))
The problem with this definition, however, is that the index expression i is evaluated twice; in the expression a[TRAP(f(), n)], for instance, f may have a side effect or take a long time to execute. I cannot introduce a temporary variable since the macro needs to expand to an expression. Also, defining TRAP as an ordinary function implies a run-time overhead and makes it harder for the compiler to optimize away the trap.
Is there a way to rewrite TRAP so that i is evaluated only once?
Edit: I'm using ANSI C89
Use the macro TRAP when the index expression doesn't contain a function call and use a (non-macro) function trap when it does. This way the function call overhead only occurs in the rarer latter case.