Phil Carmody
10/24/2009 11:33:00 AM
Keith Thompson <kst-u@mib.org> writes:
> James Dow Allen <jdallen2000@yahoo.com> writes:
>> On Oct 22, 1:51??pm, Keith Thompson <ks...@mib.org> wrote:
>>> Rule of thumb: If a ?: operator can be written equivalently as an
>>> if-else statement, write it as an if-else statement (unless it's
>>> part of a macro definition).
>>
>> I think we'd all agree that "cutesy" shortcuts to achieve a
>> false keystroke economy are wrong, but this statement goes much
>> too far. It seems to assume that "if else" is more readable
>> than "? :" but that should *not* be the case for a C programmer.
>
> I was referring specifically to cases where a ?: operator appears at
> the top level of a statement expression, and the second and third
> operands' results are discarded. For example:
>
> condition ? puts("A message") : puts("Another message");
>
> In my opinion, using ?: here is just silly; it's better written as:
>
> if (condition) {
> puts("A message");
> }
> else {
> puts("Another message");
> }
Better written as:
puts(condition ? "A message" : "Another message");
> or whatever brace style you prefer. In cases like this, the use of
> the ?: operator tells me "I know what the ?: operator is, and you
> should be impressed."
The original ?: example used ?: only for control flow, not for
selection of values. So it doesn't tell me that the author knows
that it has that latter use. The fact they avoided my version
tells me that probably they don't. So we'd both flag the line,
for mostly the same reason, but my terseness pushes me to my
one-liner rather than
>> I often string together ?, : and/or && and || into an involved
>> expression, and add newlines and tabs to make it easy to read.
>> IMHO the if/else equivalent would be harder to read because of
>> all the "if/else" clutter.
>
> Can you give an example? If it doesn't meet the criteria I mentioned
> above, so that the transformation from ?: to if-else is absolutely
> trivial, I probably wouldn't object. I don't find "if" and "else" to
> be clutter; they're just part of the code.
Sometimes they make the function easier to understand as they
clearly and cleanly frame off sections which can be considered
separately. That's not clutter at all.
> (But tabs? Spaces only, please.)
A coding standard which is 100% strict about how wide a tab is
may also approve or demand the use of tabs.
I don't personally care - I press 'tab' in emacs, and it makes
the code conform to the coding standard in effect at the time.
Phil
--
Any true emperor never needs to wear clothes. -- Devany on r.a.s.f1