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;
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Victor
  • 105
  • 4

5 Answers5

2

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.

msc
  • 33,420
  • 29
  • 119
  • 214
1

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?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

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,

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

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.

iBug
  • 35,554
  • 7
  • 89
  • 134