S
Seebs
Is there any way to write this code without an else if?
Sure!
If so how..and
can you explain it line by line please :/ I'm really new to C or
programming.
Welcome!
/* count blanks, tabs and newlines in input */
main()
You should probably spell this
int
main(void)
in modern C.
(You missed the "++" on the last one; it should be "++nl".)if (c == ' ')
++bl;
else if (c == '\t')
++t;
else if (c == '\n')
nl;
You can write this without else if as follows:
if (c == ' ')
++bl;
if (c == '\t')
++t;
if (c == '\n')
++nl;
It's not necessarily any better or more efficient, but it'll work.
The way I'd probably do it would be:
switch (c) {
case ' ': ++bl; break;
case '\t': ++t; break;
case '\n': ++nl; break;
default: break;
}
'switch' jumps to a case matching the controlling expression, then executes
code until it hits a 'break'. It's often relatively efficient for cases
where there are many options; compilers may generate smarter code than for
the corresponding sequence of else if ()s.
.... andprintf("There are %d blanks, %d tabs and %d newlines", bl, t, nl);
return 0;
here.
-s