c - 警告 : suggest parentheses around assignment used as truth value

标签 c if-statement compiler-warnings

我有这段代码,但有些东西我不明白

当我编译以下代码时:

#include <stdio.h>
#include <stdlib.h>


int main() {

double x=1;
double y=0;

  if (x!=y)
  {
    printf("x!=y\n");
  }
  if (x=y)
  {
  printf("x=y\n");
  }

  return 0;
}

我收到以下警告:警告:建议在赋值周围使用括号作为真值

当我运行程序时,我得到以下输出

x!=y
x=y

如果 if '=' 不是为了比较而是只是将 y 中的值放入 x 中,为什么要打印 x=y。

最佳答案

编译器警告您表达式x = y的结果在条件内部使用;我提到这一点,尽管它似乎与您的实际问题无关,因为这些天,通常这意味着存在拼写错误,作者打算写 == .

关于这个问题:因为x = y计算结果为y(一个double)并且y为零,结果为 false 因为这是 C 标准规定应该发生的情况。从 6.3.1.2 开始:

When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

因此,运行此代码应该不会打印“等于”消息,正如 it does for me 所示。 .

关于c - 警告 : suggest parentheses around assignment used as truth value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13160315/

相关文章:

visual-studio - 将所有图像添加到 Package.AppXManifest 会导致编译器警告

rust - 如何仅允许 dead_code 和 unused_imports 用于开发构建?

c++ - 哪种方法可以测试乘法有符号整数溢出?

c - 我的循环在某种程度上是错误的,通过在 while 循环中使用 Y/N 选项

c - STM32 : FatFs Library - f_mount

python - 如果没有命令行参数,则读取 stdin Python

c - 在 C 中使用 exp101 和 log101 函数

r - R中使用lappy时如何处理NA

c# - 是否可以在这段代码中避免使用多个 IF?

c - 在我不应该的情况下在没有警告的情况下获得分配?