4 ms·
I'm kinda surprised that the assignment-during-test thing doesn't generate a warning in the case of a switch statement. It does in other cases (if and while do
by rosser 12y ago
I'm kinda surprised that the assignment-during-test thing doesn't generate a warning in the case of a switch statement. It does in other cases (if and while do under gcc and clang, at least).
- cperciva 12y agoIf it creates warnings, you can silence them by adding extra parentheses, e.g., if ((buf = malloc(buflen)) == NULL) goto outofmemory;
- rosser 12y agoI was originally going to comment saying exactly that — under gcc and clang, at least, just the extra parens will disable the warning; no comparison necessary — but thought to test that the warning is generated in case of a switch statement (and is then disabled by the extra set of parens), which led to realizing the behavior is different. Just surprised by the inconsistency.
- loup-vaillant 12y agoCareful with that example. The parentheses here don't just remove the warning. They remove a bug. This code: if (buf = malloc(buflen) == NULL) goto outofmemory; is actually equivalent to that code: if (buf = (malloc(buflen) == NULL)) goto outofmemory; So, malloc gives you a pointer, which is compared to the null pointer, giving you either 0 or 1. And that is assigned to buf. Hopefully your compiler will warn you about the type error that spawns from such dark magic.
- deleted 12y ago[deleted]
- cperciva 12y agoOops, quite right. I was originally thinking of if ((rc = pthread_mutex_lock(mtx))) err("mutex_lock failed: %s", strerror(rc)); but decided to switch to a better-known function at the last minute and completely lost the point.
- jleader 12y agoAssignment-during-test is flagged because it's common for a typo to conflate assignment and equality-testing. Equality-testing is very common in an if or while, so an assignment inside an if or while has a fairly high likelihood of actually being a mis-typed equality-test. Switch, on the other hand, is very rarely used with an equality-test (since equality-test only returns true or false, why would you use a switch when an if would suffice?). So an assignment inside a switch is much less likely to be a mis-typed equality-test.