> My
canonical example,
> while (*T++=*S++);
> just for the sake of readability, is easier for a beginner OR
> STUDENT to
> follow as something like:
>
> do
> {
> X = *S;
> *T = X;
> S++;
> T++;
> }
> while('\0'<> X); /* Yes, of course, (X), but that's my point. */
On Thu, 5 Jan 2012, Toby Thain wrote:
ITYM !=
Probably. Certainly for my own use or second semester students.
With most C compilers either would work.<> is slightly more intuitive
for beginners than != until they recognize it as a crude drawing of a
not-equal sign. Once they've got THAT, though, they're probably ready for
while(X)
One trivial mistake of style that I made in this example, was that
because
I used 'S' for "source" and 'T' for "target", I
didn't have 'T' available
for the temporary variable name.
(Readability and ease of understanding is more important than
efficiency
for EXPLAINING something)
The long version isn't less efficient.
I meant as a general principal.
BUT, even in this example, unless the compiler does "optimization" to
compile something other than what you asked for (DWIM!) and removes the
temporary variable, the long version will be a TINY bit slower due to the
extra temporary variable being written and read, and then read again for
the comparison. In the "short" )"crammed together") version the value
is
in a register when it is needed, and presumably in the accumulator for
the
conditional jump that the while translates to. Likewise, by incrementing
the pointers separately from de-referencing them, you'll probably end up
with an an "unnecessary" retrieval of the pointer value from memory
instead of register for the de-reference.
If the purpose is the fastest possible code, that stuff matters.
If the purpose is having the students understand it, without having to
decipher the "puzzle code", delaying them moving on to the rest of the
topic, the long version is far superior.
THAT's where Holub and I don't agree - he considers the long version
to be
bordering on "WRONG", even for classroom blackboard! In one of his
columns, he actually CORRECTED similar code in a reader question (about
another issue) - I felt that ease of comprehension by his
readers/students should be a higher priority than "efficiency"
--
Grumpy Ol' Fred cisin at
xenosoft.com
... I don't even use the ternary operator in C preferring
the simpler and IMNSHO much clearer if/else construct. I've probably
even replaced the ternary critter with an if/else in code someone else
wrote that I was reworking for some reason. If it takes a microsecond
longer to execute the compiled code, who really cares the vast majority
of the time. OK, if I knew for sure the ternary was faster, I might
grudgingly use it in an interrupt routine but I would not be really
happy about it!