Anyway, what's the accepted wisdom about doing the following?
(Is it at least well defined?)
-------------
#include <stdio.h>
int mygetchar (void)
{
printf ("My getchar\n");
return getchar();
}
#define getchar() mygetchar()
All standard library functions can be #define'd as function-like
macros by the header that declares (prototypes) them, and getchar() in
particular pretty commonly is. It is a constraint violation and a
required diagnostic to re-#define an existing macro differently.
You need to #undef getchar first. Note that you don't need to put it
in #ifdef to be safe -- #undef of a nonmacro is a guaranteed no-op.
Given you do that, it should as you want go through your replacement.
7.1.3p1 does say it is 'reserved for use as a macro name' without
mentioning #undef, but p3 says that #undef of _[A-Z_]* gives U.B.
without saying the same for any other standard-reserved identifiers,
and 7.1.4p1 says that #undef of such a 'shadow' macro will allow
access to the real function; it doesn't make sense to do that without
also allowing you to #define it for your own use.
Note however that (other) <stdio.h> shadow macros could legally use
each other, including getchar() expecting to get the standard one, and
get your replacement instead. For just a wrapper like this it should
still work, but if you try to rewrite a std lib function to do
something different (and IYO better) you are courting trouble.
Whether this sort of thing is _wise_ is a whole other question.
Personally I would rather use a debugger in most cases where this
might possibly be of any use. And in the cases where a debugger
doesn't work, printf (or more generally stdout) may not be the right
answer. But that just opens up _barrels_ of worms.
int main (void)
{
char c = getchar ();
printf ("got char '%c'\n", c);
return 0;
}
<pedantic> plain char may be signed and unable to correctly represent
some values returned from getchar(), including EOF, even when
converted back to unsigned char by %c inside *printf. In most cases
including this use int. But I'm sure that wasn't your point.
- David.Thompson1 at worldnet.att.net