6

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

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user437821
  • 71
  • 1
  • 6
  • 1
    If you were using gcc, make sure you have the -Wall flag set. Amongst the many common problems it reports is this one. – JeremyP Sep 02 '10 at 13:50

3 Answers3

18

You need to place parenthesis as:

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

Precedence of != is greater than that of =

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

is same as:

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

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) or 1 (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 value 0001 in it.

You can confirm it by piping your program output to octal dump (od) :

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


$ echo '\n' | ./a.out | od -bc        # user entered '\n'
0000000

GCC when used with -Wall warns you as:

warning: suggest parentheses around assignment used as truth value
Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
codaddict
  • 445,704
  • 82
  • 492
  • 529
2

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

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

So ch gets the value 1 (for true), which is an unprintable character. You should use explicit parenthesis to fix the precedence:

 while( (ch = getchar()) != '\n') {
codaddict
  • 445,704
  • 82
  • 492
  • 529
bdonlan
  • 224,562
  • 31
  • 268
  • 324
1
ch = getchar() != '\n'

Writing this will cause unexpected behavior depending on the languages operator precedence. In C = is evaluated after != so ch will be true or false. Try:

(ch = getchar()) != '\n'
Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88