I read in K&R at page 90 that getchar is often defined as macro.
So, why does this code actually work:
#include <stdio.h>
#undef getchar
int main()
{
char c;
c= getchar();
printf("%c\n",c);
return 0;
}
I read in K&R at page 90 that getchar is often defined as macro.
So, why does this code actually work:
#include <stdio.h>
#undef getchar
int main()
{
char c;
c= getchar();
printf("%c\n",c);
return 0;
}
No. It is a Function like macro.
C99 7.1.4(P1):
Any function declared in a header may be additionally implemented as a function-like macro defined in the header,so if a library function is declared explicitly when its header is included, one of the techniques shown below can be used to ensure the declaration is not affected by such a macro.
So, why does this code actually work?
Because getchar()
is not just a macro, but a function-like macro.
Read more in How are getchar() and putchar() Macros?
Macros can be cleverly disguised as functions (in C they are called function-like macros), particularly if your preprocessor supports expression statements.
So long as getchar()
does what the C standard mandates what it ought to do, it could be (i) a macro, (ii) a function, or even (iii) hardcoded into the compiler itself.
These days, it's unlikely that getchar()
is implemented as a macro.
Reference: Function-like Macros.
Nope, the C standard defines getchar()
as a function. See C11
, chapter 7.21.7.6, The getchar
function. It is prototyped in <stdio.h>
header file.
Any implementation, if chose to define this as a MACRO, then it's limited to that implementation only. Point to note, it's not non-conformance. From chapter §7.1.4 (emphasis mine)
Any function declared in a header may be additionally implemented as a function-like macro defined in the header,
getchar()
is not necessarily a macro. I don't know why K&R claim that but it's possible that in earlier days it was de facto.