Why does this C program print strange characters in the output?

I have 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 this weird char that I see?

Stackoverflow doesn't print weird char. You can see it here: http://ideone.com/EfZHr

+6
c operator-precedence control-characters getchar
source share
3 answers

You need to place the brackets as:

 while( (ch = getchar()) != '\n') 

Priority != Greater than =

 while( ch = getchar() != '\n') 

matches with:

 while( ch = (getchar() != '\n') ) 

which reads char, compares it with a new line, and then assigns the comparison result to ch. Now the result of the comparison is 0 (when entering a new line) or 1 (when anything else is entered)

The strange char you see is a char control with a value of 1 , for ASCII 1 there is no character to print, so I assume that its shell prints a strange char with a value of 0001 .

You can confirm this by executing the output of your program in octal dump (od):

 $ echo 'a' | ./a.out | od -bc # user entered 'a' 0000000 122 145 141 144 040 001 012 R ead 001 \n here you go ----------------^ $ echo '\n' | ./a.out | od -bc # user entered '\n' 0000000 

GCC when used with -Wall warns you how:

 warning: suggest parentheses around assignment used as truth value 
+18
source share

C (and C ++) interpret the while loop as:

 while( ch = (getchar() != '\n')) { 

So, ch gets a value of 1 (for true), which is a non-printable character. Explicit parentheses should be used to fix priority:

  while( (ch = getchar()) != '\n') { 
+2
source share
 ch = getchar() != '\n' 

Recording this will lead to unexpected behavior depending on languages operator precedence . In C = evaluates after != , So ch will be true or false. Try:

 (ch = getchar()) != '\n' 
+1
source share

All Articles