Hello,
I tried to code one of the exercises in K&R, namely the one in which you are supposed to read the input and output it one word per line.
I've come up with two functions, the only difference being in the else block. I think the else block in the first function shows better coding practice (the variable "state" gets changed only when necessary) whereas in the second function it is more compact.
Which of those two functions would you choose?
I tried googling this exercise and most sample answers prefer the second example, which surprises me.
Code:
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
void output1()
{
int c, state;
state = OUT;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t')
{
if (state == IN)
{
putchar('\n');
state = OUT;
}
}
else
{
if (state == OUT)
state = IN;
putchar(c);
}
}
}
void output2()
{
int c, state;
state = OUT;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n' || c == '\t')
{
if (state == IN)
{
putchar('\n');
state = OUT;
}
}
else
{
state = IN;
putchar(c);
}
}
}