是否"cout<<(char *)NULL"进行"close(1)"操作这里? [英] Does "cout<<(char*)NULL" doing "close(1)" here?
问题描述
在以下代码中,在此行之后,我使用了 cout<<(char *)NULL;
,我的程序未在输出屏幕上打印任何内容.这是否意味着我在这里用 cout
完成了 close(1)
?这里到底发生了什么?这是一个错误吗?请分享您的想法.
In the following code I have used cout<<(char*)NULL;
after this line, my program printing nothing to the output screen. Does it mean I have done close(1)
with cout
here? What is actually happening here? Is this a bug? Please share your thoughts.
#include<iostream>
using namespace std;
void f(){
cout<<"\nfun\n";
}
main(){
cout<<(char*)NULL;
f(); //not getting printed !
cout<<"\nhello\n"; //not getting printed !
cout<<"hii how are you?"; //not getting printed, why??
}
我已经使用gcc和DevCpp编译器尝试了此操作,观察到了相同的行为.
I have tried this with both gcc and DevCpp compilers, same behavior observed.
推荐答案
在这里,您在流上设置了 badbit
,这导致在 cout<<<(char *)之后不打印任何内容NULL;
Here you sets the badbit
on the stream which causes nothing to be printed after cout<<(char*)NULL;
if (!__s)
__out.setstate(ios_base::badbit);
该标准说: requires:不得为空指针
.因此,您的程序肯定具有未定义的行为,应该对其进行修复.您可以使用 cout.clear()
清除不良位.
The standard says: requires: shall not be a null pointer
. So your program definitely has the undefined behavior and it should be fixed. You can clear the bad bit by using cout.clear()
.
在您的情况下, cout<<(char *)NULL;
会导致未定义的行为.但是GCC会安全播放.
In your case, cout<<(char*)NULL;
causes undefined behavior. But GCC plays it safely.
希望这会有所帮助!
这篇关于是否"cout<<(char *)NULL"进行"close(1)"操作这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!