在下面的代码我用过cout<<(char*)NULL;这一行后,我的程序没有打印到输出屏幕.这是否意味着我已经做了close(1)与cout这里?这里到底发生了什么?这是一个错误吗?请分享你的想法.
#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??
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了gcc和DevCpp编译器,观察到相同的行为.
cout << (char *)NULL导致未定义的行为.什么事情都可能发生.(编译器假定您在生成汇编代码时不执行此操作).
char *这里使用的参数必须指向以null结尾的字符串中的字符.
在这里您在流上设置badbit,这会导致之后不打印任何内容cout<<(char*)NULL;
if (!__s)
__out.setstate(ios_base::badbit);
Run Code Online (Sandbox Code Playgroud)
标准说:requires: shall not be a null pointer。所以你的程序肯定有未定义的行为,应该修复它。您可以使用 清除坏位cout.clear()。
在您的情况下,cout<<(char*)NULL;会导致未定义的行为。但 GCC 的做法是安全的。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
389 次 |
| 最近记录: |