问题
Some of the examples in K&R don't work in Code:Blocks when I type them exactly. For example, this program:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
When I type this code and run it, the program either freezes or doesn't do anything when I press enter.
The program below does the same thing (count characters in a string) and it works.
#include <stdio.h>
int main()
{
char s[1000];
int i;
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
return 0;
}
Am I missing something here? Has C been changed since K&R 2nd Edition or am I doing something wrong?
回答1:
When you press enter, you send \n
into the standard input stream(and flushes other data into the stdin
,if any). This character(\n
) is not the same as EOF
. To send EOF
, press following keys combinations:
- CTRL Z and then Enter in Windows.
- CTRL D in Unix/Linux/OSX
回答2:
C has been changed since that book was written, but even still the code is not well-defined/valid C under any version of the standard.
If you compile using the current C standard (C11), or the previous (C99), a strictly conforming compiler (such as gcc -std=c11 -pedantic-errors
) will give an error: main must return int. The old "implicit int" feature was removed in C99.
If you compile using the old C90 standard, the code invokes undefined behavior, because there is no return statement. This was allowed in C90 but it is not safe, it could cause program crashes etc. Invoking undefined behavior is always a bug, and therefore very bad practice.
(In C99, functions returning a value must have a return statement, with the exception of main(), where return can be safely omitted. So you could omit the return statement of main() if you compile as C99.)
Simply correct the code as you have already done, and it will compile in any version of the standard, without invoking undefined behavior.
来源:https://stackoverflow.com/questions/29746522/why-is-some-code-from-kr-not-working-in-codeblocks