3 ms·
Because while ((c = getchar()) != EOF) { // } Is considered more idiomatic and readable than any alternatives that's not assigning to c withi
by noselasd 9y ago
Because
while ((c = getchar()) != EOF) {
//
}
Is considered more idiomatic and readable than any alternatives that's not assigning to c within the conditional.
You'll see similar idioms in many other languages, e.g.
while((line = reader.readLine()) != null) {
}
But if you're talking about e.g.
if (foo = (bar & 0xf)) {
}
It's just bad style ...
- prewett 9y agoI think it's more idiomatic because otherwise you have to do: char c = EOF; while (c != EOF) { c = getchar(); ... } The idiomatic way reads better: "while next character is not EOF". Your (excellent) example of bad style is bad because it reads poorly: "if the result of the assignment of bar & 0xf to foo is true". Not only that, but it is not obvious what the result of an assignment is, if anything. (Yes, I do know it is the value, but personally, I think <nothing> is a more logical result).
- masklinn 9y agoDon't you mean char c = getchar(); while (c != EOF) { c = getchar(); … } ? Which not only reads badly but requires writing the "producer" twice. Though alternatively you could: while (1) { c = getchar(); if (c == EOF) { break; } ... }
- tbirdz 9y agochar c; do { c = getchar(); } while (c != EOF);
- noselasd 9y agoThis is worse, in most cases as you normally want to do something to c after you have read it, forcing you to re-check the condition int c; //a char can't represent EOF do { c = getchar(); if (c != EOF) { //do stuff } } while (c != EOF);