Silidrone
Silidrone

Reputation: 1581

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:

*

Upvotes: 1

Views: 83

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

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.

Upvotes: 4

Related Questions