问个C语言的问题,验证布尔表达式getchar() != EOF的取值是0还是1.

2013-06-24 01:22:06 +08:00
 echo1937
源码:
#include <stdio.h>

int main(int argc, char const *argv[])
{
int c;
while( c = getchar() != EOF )printf("%d \n", c);
printf("%d - at EOF \n",c );
return 0;
}

系统环境:Mac OS X 10.8.4

Clang编译报错:
$clang -v
Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.4.0
Thread model: posix

$clang 1-6.c
1-6.c:34:11: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
while( c = getchar() != EOF )
~~^~~~~~~~~~~~~~~~~~
1-6.c:34:11: note: place parentheses around the assignment to silence this warning
while( c = getchar() != EOF )
^
( )
1-6.c:34:11: note: use '==' to turn this assignment into an equality comparison
while( c = getchar() != EOF )
^
==
1 warning generated.

Gcc编译可以通过:
$gcc -v
Using built-in specs.
Target: i686-apple-darwin11
Thread model: posix
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)

但是结果很诡异,多出一个1来,
$./a.out
qaz
1
1
1
1

clang编译不通过好理解,gcc下面为什么多出个1呢.
1354 次点击
所在节点    C
9 条回复
darasion
2013-06-24 01:33:50 +08:00
回车也算.
edgar
2013-06-24 12:08:24 +08:00
clang那个是警告吧,而且你的gcc版本比较低,高版本的应该也会报错。
edgar
2013-06-24 12:33:28 +08:00
还有就是,那个1其实是getchar() != EOF的结果,改成(c=getchar())!=EOF应该就可以了
dndx
2013-06-24 12:39:50 +08:00
c = getchar() != EOF

因为 != 的优先级比 = 高,上面的代码等同于:

c = (getchar() != EOF)

所以你的 c 变量在检测到 EOF 之前都是 0 ,估计不是你想要的效果。

改成

(c = getchar()) != EOF
cmi
2013-08-07 00:58:07 +08:00
这题是K&R的Exercise 1-6吧?题目本来就是要验证 getchar() != EOF 的取值是0还是1。

多一个1是因为“回车也算.”。:)

我不明白的地方在于:
由于while (expression)的expression在此例里总是不为0,while循环无法结束,printf("%d - at EOF \n",c )永远无法执行,但是我想让这一句打印出来。

依照系统,EOF被定义为(-1),

#ifndef EOF
# define EOF (-1)
#endif

我即使输入(-1),也无法让getchar() == EOF,这是什么原因?我哪里理解错了?
cmi
2013-08-07 01:05:20 +08:00
刚回复完似乎有点明白了,即使getchar() == EOF,也只不过是给 c 赋了另外一个条件,并没有让c=0,所以while永远无法结束。
但是将一个条件赋予c,这算是什么语法?

这么理解正确吗?
cmi
2013-08-07 01:13:56 +08:00
好像还不对。
这么测试总是要输入回车,这导致getchar() != EOF永远为真。
echo1937
2013-08-07 08:40:59 +08:00
@cmi 感谢你的回复,这个问题我去看了英文版,答案和中文版是不一样的.


英文版的答案是:

#include <stdio.h>

int main(void)
{
printf("Press a key. ENTER would be nice :-)\n\n");
printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF);
return 0;
}

看来是中文版的问题吧.
vtvincy
2015-02-04 23:38:18 +08:00
兩個答案都是正確的, 回車也是一個字符所以多出來一個1
看看這篇文章會有幫助:
http://www.ruanyifeng.com/blog/2011/11/eof.html

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/73379

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX