0

I am writing little program for encoding characters and I have a problem with reading NUL characters maybe also with another ones. My problem is that getchar in this code somehow ignores the NUL characters entered by CTRL + @ .

while ((numberOfRead < 40) && (character = getchar()) && (character != EOF) && (character != '\n')) { ... }

But this code works correctly and reads the NUL characters properly.

character = getchar();
while ((numberOfRead < 40) && (character != EOF) && (character != '\n')) {
    numberOfChars++;
    ...
    character = getchar();
}

What is the difference causing the problem? Thanks for any explanation of this behaviour. Code was tested on Windows 8.1, under gcc 4.7.1

c0ntrol
  • 908
  • 2
  • 9
  • 14
  • 1
    This is why you should avoid assignment inside conditions, makes it very easy to write bugs. – Lundin Mar 07 '16 at 10:55
  • ^^^ what @Lundin says. I looks clever and cool, but doesn't actually work:( Simple, one step at a time code, seemingly avoidable intermediate temp vars etc. result in working. or at least debuggable, code. Complex, compound boolean expressions result in posts to SO:( – Martin James Mar 07 '16 at 11:02
  • I like the idea of using this assignment in the conditions due to many examples in the K&R, which I had read recently. :) – c0ntrol Mar 07 '16 at 18:01

1 Answers1

1

Here:

    while (... && (character = getchar()) && ...) ...

you use the value of character as truth value. When the read character is the null character with the value 0, this condition is false.

You can do something like:

    while (numberOfRead < 40
       && (character = getchar()) != EOF && character != '\n') { ... }

but I find your second variant with the getchar outside the condition more readable.

M Oehm
  • 28,726
  • 3
  • 31
  • 42
  • I had absolutely forgotten about the evaluating the assignment. :) – c0ntrol Mar 07 '16 at 17:58
  • Yes, it's easy to miss in compound conditions. (That's why I prefer your second variant where it's clear where the `getchar` is called.) – M Oehm Mar 07 '16 at 18:18