So currently I'm learning C from the C programming language 2nd edition book and it says that:
while (c = getchar() != EOF) { } is identical to:
while (c != EOF) { c = getchar(); } However, when I run the code I just had written:
#include <stdio.h> int main() { char c; int times; while (c = getchar() != EOF) { if (c == 'a') { ++times; } } printf("%d\n", times); } The value of times it outputs is 0 instead of actual value of times I typed in 'a' character. Now in this code, it works fine:
#include <stdio.h> int main() { char c; int times; while (c != EOF) { c = getchar(); if (c == 'a') { ++times; } } printf("%d\n",times); } and if I type a 3 times, the value it outputs is 3.
cto be of typechar? Remember,getcharreturns anint.timesis uninitialized, incrementing it is undefined behaviour.cis also uninitialized in the second version on the first time thewhilecondition is checked.(c = getchar()) != EOFas an example, and on page 153 it shows that while loop with correct parentheses, but I do not see where it shows that while loop with parentheses missing as it is shown in the question. What page did you copy this from? If the parentheses were in the book and you removed them, then you should remember that computers are mechanical and being precise matters. Source code from books should be reproduced exactly.