Re:Yoda conditions
by stochastic_monk on Thursday August 15, 2019 @10:12AM
(#20705358)
It’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.> 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.
Re:Yoda conditions
by marcosdumay on Thursday August 15, 2019 @10:19AM
(#20705417)
That'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.
This would achieve the same but is far more readable:
while(status != SUCCESS) {
status = syscall(...);
// do something with status
}Only if status is initialised to something other than SUCCESS.
So use a do-while instead.
And this introduces another bug: it'll run the loop body even if syscall fails the first time it's run.
I'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
}
Likewise:
Or something like that. I don't understand the hate, just make sure it's obvious what you're doing.