从int强制转换为bool时出错

error in casting from int to bool

本文关键字:bool 出错 转换 int      更新时间:2023-10-16

以下程序:

#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