I’ve the following program:
#include <stdio.h>
int main()
{
int ch;
while( ch = getchar() != '\n') {
printf("Read %c\n",ch);
}
return 0;
}
No matter what I enter I get:
Read
Why is this happening and what is that weird char that I see?
Stackoverflow is not printing the weird char. You can see it here: http://ideone.com/EfZHr
You need to place parenthesis as:
Precedence of
!=is greater than that of=is same as:
which reads a char compares it with newline and then assigns the result of comparison to ch. Now the result of comparison is
0(when newline is entered) or1(when anything else is entered)The weird char you’re seeing is the control char with value
1, there is no printable symbol for ASCII 1, so I guess its the shell that prints the weird char with value0001in it.You can confirm it by piping your program output to octal dump (od) :
GCC when used with
-Wallwarns you as: