Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are both these two cleaning buffer methods equivalent?

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

like image 528
Gustavo Duarte Avatar asked May 04 '26 08:05

Gustavo Duarte


1 Answers

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.

like image 185
Vlad from Moscow Avatar answered May 07 '26 00:05

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!