c++ - 我可以在 C++ 中对 int 值使用 not 运算符吗?

标签 c++ int logical-operators negation

奇怪的问题,但有人向我展示了这个, 我想知道你可以使用 not ! C++ 中的 int 运算符? (对我来说很奇怪)。

#include <iostream>
using namespace std;

int main()
{
   int a=5, b=4, c=4, d;
   d = !( a > b && b <= c) || a > c && !b;
   cout << d;
   system ("pause");
   return 0;
}

最佳答案

是的。对于整数类型,!返回 true如果操作数为零,则 false否则。

所以 !b这里只表示b == 0 .


这是将值转换为 bool 的特殊情况。 . !b可以查看!((bool)b)所以问题是b 的“真相”是什么? .在 C++ 中,算术类型、指针类型和枚举可以转换为 bool .当值为 0 或 null 时,结果为 false , 否则为 true (C++ §4.1.2)。

当然自定义类甚至可以重载operator!operator <类型可以转换为 bool> 以允许 !b为他们的课。例如,std::stream已重载 operator!operator void*用于检查故障位,所以成语喜欢

while (std::cin >> x) {   // <-- conversion to bool needed here
  ...

可以使用。

(但您的代码 !( a > b && b <= c) || a > c && !b 只是神秘。)

关于c++ - 我可以在 C++ 中对 int 值使用 not 运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4123550/

相关文章:

c++ - 未初始化变量的值从何而来?

groovy - 在 IntRange 上调用 .each{} 返回范围而不是每个整数

java - 斐波那契的上限

powershell - PowerShell强制[int]换行(IP到Long的转换)

rust - 在 Rust 中左移 (<<) 时如何惯用地测试溢出?

R:If 语句包含 is.null 作为通过 OR 连接的条件之一

c++ - 如何用 C++ 中的整数替换 char 数组中的某些项?

c++ - 将 MinGw 编译器集成到 Dev C++ 中

C++ 伪随机数生成器线程安全吗?

r - 无法从逻辑上解决 rasterToPoints 提取的 x,y 值