while((garbage = getchar()) != '\n' && garbage != EOF)
;
is basically a very compressed version of:
garbage = getchar();
while ( garbage != '\n' && garbage != EOF )
garbage = getchar();
Basically, read and discard any characters on standard input until we see a newline or end of file is signaled.
C condition expressions can contain an assignment:
while ( x = foo() ) // assign result of foo() to x, loop if non-zero
{
// do something
}
Since a lot of people accidentally type =
when they mean ==
, most compilers will warn about an assignment expression in a condition expression unless that expression is wrapped in parentheses:
while ( (x = foo()) ) // assign result of foo() to x, loop if non-zero
{
// do something
}
This tells the compiler "yes, I intend to assign the result of foo()
to x
and loop based on the result, shut up."
Assignment expressions in C can appear as part of a larger expression. The result of an assignment expression is the value stored in the target after any appropriate conversions. Thus, the result of an assignment expression can be compared against something else as well, so you can write
while ( (x = foo()) > 0 ) // assign result of foo() to x, loop while result is positive
{
// do something
}
You can make multiple comparisons:
while ( (x = foo()) > 0 && x < 100 )
{
// do something
}
The &&
operator forces left to right evaluation - (x = foo()) > 0
will be evaluated first, assigning a new value to x
as a side effect. If the result is non-zero (x
is positive), then x < 100
will be evaluated. Again, it's a compact way of writing:
x = foo();
if ( x > 0 && x < 100 )
{
// do something
x = foo();
}