【问题标题】:What is the meaning of "if (x) { … }" where x is an integer in C++? [duplicate]“if (x) { ... }”是什么意思,其中 x 是 C++ 中的整数? [复制]
【发布时间】:2016-05-25 03:15:05
【问题描述】:

我看到了一些令我困惑的 c++ 语法

int x = 10;
if(x){ //this line confused me
//code 
}
else{
//code 
}

我不明白这是什么有效代码,if(x) 是做什么的?

【问题讨论】:

  • Nitpick:可能是语义(使用int 作为if 条件)让您感到困惑,而不是语法(文本if(x){)。

标签: c++ if-statement syntax


【解决方案1】:

int 隐式转换为bool。任何非零的int 的计算结果为true。零整数转换为false。在您的情况下,该行基本上测试x 是否不同于零,它与

if(x != 0) ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 2013-08-17
    • 2017-01-17
    • 2019-08-06
    • 2016-07-18
    • 2020-03-18
    • 2021-08-02
    相关资源
    最近更新 更多