从int强制转换为bool时出错
error in casting from int to bool
以下程序:
#include<iostream>
using namespace std;
void f(int x){
if(x)cout<<x;
}
int main(){
int x=3;
f(x);
return 0;
}
输出为:
3
c++中除了0以外的任何数字都被认为是真的,难道不应该没有输出吗?但是,如果我将上述程序更改为:
#include<iostream>
using namespace std;
void f(int x){
//changed here
if(x==0)cout<<x;
}
int main(){
int x=3;
f(x);
return 0;
}
程序运行正常,即没有输出。有人能帮我吗???
c++中除了0以外的任何数字都被认为是真的,难道不应该没有输出吗?
正如你所说,除了0以外的任何数字都被认为是真的。3不是0,所以3是真的。
在if
语句中使用int
时,存在一个隐含的!= 0
。这两种说法是等价的:
if (x) cout << x;
if (x != 0) cout << x;
当x == 3
。
相关文章:
- 写入向量<向量<bool>>
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 为x86而非x64编译时出错
- 在类外部定义显式运算符 bool() 时出错
- 使用bool非类型参数实例化类模板时出错
- 从int强制转换为bool时出错
- 将矢量bool复制到CUDA内存时出错
- 用于初始化 std::vector<std::function<bool(std::string)的初始值设定项列表> >在 g++ 4.9.0 中出错,但使用 Visual