How are getchar() and putchar() Macros?

Home / c# / How are getchar() and putchar() Macros?

From what I understand about macros in C, they are predefined constants that will be used throughout the program with their constant value, so we go ahead and define them to avoid further complications and make the code more readable, so people reading it will understand what is supposed to stay constant and what isn’t.

I have read here and there (C programming A Modern Approach, K.N King) that we can define these two functions as macro.

Since I’m somewhat new to C, I can’t wrap my head around how can these two be defined as macro?

There are two types of macros: simple substitution macros and function-like macros.

Substitution macros replace one instance of a symbol with another. For example:#define LEN 10
char str[LEN];
After preprocessing, this becomes:char str[10];
A function-like macro can take parameters that can be plugged in to whatever gets substituted:#define MAX(a,b) ((a) > (b) ? (a) : (b))
int x = MAX(2,3);
After preprocessing:int x = ((2) > (3) ? (2) : (3));
In the case of getchar and putchar, they can be defined as follows:#define getchar() getc(stdin)
#define putchar(c) putc(c, stdout)
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *