"Spiros Bousbouras" <spibou@gmail.comwrites:
Quote:
So far we've had 3 versions of code performing the
task which is exercise 1-10 in K&R2:
Quote:
VERSION 1
int main() {
int c;
while ((c = getchar()) != EOF) {
putchar(c);
if (c == ' ') {
while ((c = getchar()) == ' ') if (c == EOF) return 0;
putchar(c);
}
}
return 0;
}
Quote:
VERSION 2
int main(void) {
int c, blank = 0;
while((c = getchar()) != EOF) {
if(c == ' ') {
if(!blank) {
blank = 1;
putchar(c);
}
} else {
blank = 0;
putchar(c);
}
}
return 0;
}
Quote:
VERSION 3
int main(void) {
int ch, last = 0;
while ((ch = getchar()) != EOF) {
if (last != ' ' || ch != ' ')
putchar(ch);
last = ch;
}
return 0;
}
[cut]
Quote:
Personally I prefer version 1 because versions 2 and
3 have an extra assignment at every iteration of the
loop. On some platforms this *will* make a difference
in performance.
There are only two integers which both will probably be stored in
registers so a single "mov reg, reg" instruction won't make a big
difference IMO.
Quote:
Even if it won't or the difference in
performance turns out to be miniscule (and that will almost
certainly turn out to be the case on every realistic
input) it still does not agree at all with my sense of
aesthetics to introduce extra instructions in such a
blatant manner.
>
Apart from that I actually consider version 3 the
harder to write and verify.
IMO the 3rd version is the easiest to write and understand. It's
straightforward, ie. the exercise is about printing all characters
unless it is a space and the previous character was a space, so if the
previous character (last != ' ') was not a space or this character is
not a space (ch != ' ') we shall print the character.
Moreover, there is only one way the loop may stop (ie. the loop
condition) and the first version involves return statement to stop the
loop which some prefer to avoid (just like break statement).
Only I would do:
#v+
#include <stdio.h>
int main(void) {
int ch, last = 0;
while ((ch = getchar()) != EOF) {
if (last != ' ' || ch != ' ') {
putchar(last = ch);
}
}
return 0;
}
#v-
--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>--<jid:mina86*jabber.org>--ooO--(_)--Ooo--