How much is it possible to do fake-functions with macros in C?
Every time people said that macros are unsafe, also that they are not
(directly) type-checking on their arguments, and so on. Worst: when errors
occur, the compiler gives intrincated and incomprehensible diagnostics,
because the macro did just a mess.
Is it possible TO USE macros in almost the same way as a function, by
having safe type-checking, avoiding typical pitfails and in a way that the
compiler launchs the RIGHT diagnostic.
I am going to answer this question (auto-answering) in an affirmative way.
I want to show you the solutions that I've found to this problem.
The standard C99 will be used and respected, to have an uniform underground.
But (obviously there is a "but"), it will "defined" some kind of "syntax"
that people would have to "eat".
This special syntax intents to be the most simple to write, as much as,
the most easy to understand and/or handle, minimizing the risks of ill
formed programs, and more importantly, obtaining right diagnostic messages
of the compiler.
Finally, it will be studied two cases: "non-returning value" macros (easy
case) and "returning-value" macros (not-easy, but more interesting case)
Let us quickly remember some typical pitfails produced by macros.
Example 1
#define SQUARE(X) X*X
int i = SQUARE(1+5);
Intended value of i: 36. True value of i: 11 (with macro expansion:
1+5*1+5). Pitfail!
(Typical) Solution (Example 2)
#define SQUARE(X) (X)*(X)
int i = (int) SQUARE(3.9);
Intended value of i: 15. True value of i: 11 (after macro expansion: (int)
(3.9)*(3.9)). Pitfail!
(Typical) Solution (Example 3)
#define SQUARE(X) ((X)*(X))
It works fine with integers and floats, but it is easily broken:
int x = 2;
int i = SQUARE(++x);
Intended value of i: 9 (because (2+1)*(2+1)...). True value of i: 12
(macro expansion: ((++x)*(++x)), which gives 3*4). Pitfail!
A nice method for type-checking in macros can be found here:
How to verify a type in a C macro? (by J. Gustedt)
However I want more: some kind of interface or "standard" syntax, and a
(little) number of easy-to-remember rules.
The intent is "be able TO USE (not to implement)" macros as much as
similar to functions.
That means: well written fake-functions.
Why is that interesting in some way?
I think that is an interesting challenge to achieve in C.
How much is it possible to fake-functions with macros?
Is it useful?
You tell me.
No comments:
Post a Comment