Muhamed Cicak Muhamed Cicak - 2 months ago 12
C Question

C getchar() misunderstanding

Can someone explain me the code ?? Wouldn't

d
be always equal to
c
? I guess I don't really get this
getchar()
function.Why isn't
d
always equal to `c ?

#include<stdio.h>

void test(int c);

int main(void) {
int c;
while ((c = getchar()) != EOF) {
test(c);
}
return 0;
}

void test(int c) {
int d;
if (c == '/') {
d = getchar();
printf("%c", d);
}
}


Input:


/*


Output:


*

Answer

No, not really. As mentioned in C11, chapter ยง7.21.7.6, The getchar function, (emphasis mine)

The getchar function returns the next character from the input stream pointed to by stdin. [...]

So, each call to getchar() will give you the next character input present in the input stream. So, when c == '/' condition is met, it will read the next entry and store into d, it need not be the same as c, anyway.