Re: Is this C?
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 30 Nov 2007 08:48:00 -0500
Duncan Muirhead wrote:
I came across code somewhat like this, and was somewhat
puzzled by it. Is it C, or does gcc just compile it (" gcc -Wall -std=c89 -pedantic odd.c eg.c -o odd")
without complaints?
The idea is to override a function by defining a new function with an extra argument, and a macro.
(The reason was that in the real code the function
being replaced was called many times, and the aim
was to gather more diagnostic information in debugging
without having to change all the calls).
eg.c:
#include <stdio.h>
void printit( int it)
{ printf( "It: %d\n", it);
}
odd.c:
#include <stdlib.h>
#include <stdio.h>
void new_printit( int it, char* who)
{ printf( "%s: It's %d\n", who, it);
}
#define WHO "main"
#define printit( i) new_printit( i, WHO)
#include "eg.h"
int main( int argc, char** argv)
{ printit( argc);
(printit)( argc);
return EXIT_SUCCESS;
}
eg.h:
void (printit)( int it);
The bits that I find puzzling are:
a. "(printit)" in eg.h. Without the brackets, of course, the
printit macro is invoked and syntax errors arise. b. "(printit)" in odd.c. This means that the printit() from
eg.c gets called, not the macro.
So it looks as if the preprocessor does not replace (printit)
with (<bodyofprintit>). Is this C? Is this only because the
printit macro takes parameters?
Yes and yes. The invocation of a function-like macro
consists of the macro name followed by a parenthesis-enclosed
list of its arguments (possibly empty). The name in any other
context is not a macro invocation, and the preprocessor just
leaves it alone. Hence
printit(argc) -- invokes the printit macro and expands
it to new_printit(argc, WHO)
(printit)(argc) -- not a macro invocation, no expansion
"printit(argc)" -- not a macro invocation
printit /**/ (argc) -- invokes and expands the printit
macro, because comments and white space don't matter
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.
- References:
- Is this C?
- From: Duncan Muirhead
- Is this C?
- Prev by Date: Re: Is this C?
- Next by Date: Re: Compiler problem....unique to C or compiler???
- Previous by thread: Re: Is this C?
- Next by thread: << HUNDSOME GAIN WITHOUT INVEST ON NET>>
- Index(es):
Relevant Pages
|