3

I was wondering:

do they do exactly the same thing? calling c = getchar on expression is the same as doing it with a do...while loop?

void clrbuf(void)
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}
void clrbuf(void)
{
    int c;
    do c = getchar(); while (c != '\n' && c != EOF);
}

edit: c was once typed char, but folks told me int was the appropriate type for it

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

3

For starters the variable c should be declared like

int c;

because if the type char behaves as the type unsigned char then this condition

c != EOF

will be always true.

According to the C Standard (7.21 Input/output <stdio.h>)

EOF

which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

So if the type char behaves as the type unsigned char (this depends on compiler options) then the value stored in the variable c after the integer promotion to the type int will be still a non-negative value.

The first while loop

while ((c = getchar()) != '\n' && c != EOF);

may be rewritten using the comma operator like

while ( c = getchar(), c != '\n' && c != EOF );

that is in fact it consists of two parts: the assignment expression c = getchar() and the condition c != '\n' && c != EOF.

As you can see it is equivalent to the do-while statement

do c = getchar(); while (c != '\n' && c != EOF);

However the first while loop

while ((c = getchar()) != '\n' && c != EOF);

is more expressive and clear.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335