CBFalconer said:
Yes, that's an improvement.
Yes, that's also an improvement.
Your book is obsolete and wrong. C99 requires the int in the
declaration of main, and the void for parameters is just good
practice. C99 will supply a default return value, but earlier
standards don't. Thus your code is wrong for any version.
Neither version of the standard defines the term "wrong", so it's not
clear what you're talking about.
The declaration "main()" is legal for C90. (There's a subtle argument
that the void keyword might be necessary, but since ANSI was careful
not to break existing code, it was clearly the intent that
"main() { ... }" should be acceptable.)
Support for C90 is much more widespread than support for C99, and even
compilers that do support C99 will almost certainly do no more than
issue a warning for the implicit int return type. (Which is not to
say that such a warning should be ignored, of course.)
As for the missing return statement, in C90 that merely causes an
undefined status to be returned to the calling environment. If the
environment doesn't use the status (say, if you type "./prog" to a
Unix shell), then this likely won't make any difference; at worst, it
might result in some harmless message after the program terminates.
Having said that, yes, both changes you suggest are certainly
improvements, but they don't necessarily tranform the program from
being "wrong" to being "right".
If it doesn't work with the above simple changes, your compiler
system is fouled.
If the above simple changes make any relevant difference to the
behavior of the program, I'll be astonished. We now know what the
problem was, and it would have shown up in exactly the same way with
your suggested changes in place.
I probably would have mentioned these things myself if they hadn't
already been covered by others. Actually, though, what bothered me
more was the way the source code was formatted. Here's a modified
version of the program with your changes and better layout (I also
added a pair of braces):
#include <stdio.h>
/* count characters in input; 1st version */
int main(void)
{
long nc;
nc = 0;
while (getchar() != EOF) {
++nc;
}
printf("%ld\n", nc);
return 0;
}
The point here (I'm addressing the OP now) is that consistent
indentation makes the structure of the program much easier to see. It
doesn't matter much for something this small, but it's vital for
larger and more complex programs, and it's a good idea to get into the
habit as early as possible.