If I type the words "Hello World" into the standard input stream, this program will print out weird box symbols instead of the expected "Hello World" back into standard output.
#include <stdio.h>
int main(void)
{
// print out all characters from the stream until '/n' character is found
int ch;
while (ch = getchar() != '\n')
{
putchar(ch);
}
putchar('\n');
}
I am aware of how to fix the problem. But why is this line of code incorrect?
while (ch = getchar() != '\n')
x_eq_y = x == y
was interpreted as(x_eq_y = x) == y
, as a silly example. C has some wonky precedences though (which have been acknowledged by the authors as being a mistake, but are still emulated by other languages for compatibility). For example,x == y << z
is the same asx == (y << z)
as you'd expect, whilex == y & z
is the same as(x == y) & z
. – MultivocalWTF operator precedence
every 5 minutes. Either separate compound statements or use explicit parentheses. In any other case you're asking for trouble or forcing it upon other people. – Denver