5 ms·
I think this is reasonable readable: while ((status = systemcall(...)) != SUCCESS) { do something with status; } Leave a comment there explain
by beatgammit 7y ago
I think this is reasonable readable:
while ((status = systemcall(...)) != SUCCESS) {
do something with status;
}
Leave a comment there explaining the assignment.
Likewise:
if ((status = systemcall(...)) != SUCCESS) goto error;
Or something like that. I don't understand the hate, just make sure it's obvious what you're doing.
- Sahhaese 7y agoThis would achieve the same but is far more readable: while(status != SUCCESS) { status = syscall(...); // do something with status }
- taneq 7y agoOnly if status is initialised to something other than SUCCESS.
- blktiger 7y agoSo use a do-while instead.
- Izkata 7y agoAnd this introduces another bug: it'll run the loop body even if syscall fails the first time it's run.
- dpzmick 7y agoI've been going with this style for things like reading files (with retries) or any sort of loop that feels awkward. while (1) { int ret = ...; if (ret == ...) break; if (ret == some_other_condition) break; // additional termination conditions.... // do exactly one thing }
- Izkata 7y agoYour transformation has introduced a bug: the loop body will run once after success turns false.
- stochastic_monk 7y agoIt’s traditional to build these kinds of loops in C, e.g.: int c; while((c = getopt(argc, argv, argstr)) >= 0) {...} I’d say it’s acceptable, and Python is adding syntax so it can mix assignments and checks.
- marcosdumay 7y agoThat's perfectly fine and arguably even better than the alternatives. The `a = b = c = 0;` format is also good. But enabling it on the language level brings a large amount of risk and complexity just for what amounts to a micro-optimization.
- 08-15 7y ago> Leave a comment there explaining the assignment. Please don't. This is a perfectly understandable idiom in C. Don't explain the language in your comments; that's the job of a text book, which should be read by anyone before they read your code.