c - 使用逗号运算符的意外输出

标签 c if-statement

我写了一个程序

#include<stdio.h>
int main()
{
      int x=3;
       if((x)==1,2,4,5,6)
               printf("number found in the list\n");
       else
               printf("Number not found \n");

      return 0;
}

我期望输出是“未找到号码”,但它是“在列表中找到号码”,为什么会这样

最佳答案

== 运算符的优先级高于 ,,因此 if 子句的计算结果为

if (((x) == 1),2,4,5,6)

自从逗号运算符的最后一个“元素”“计数”(6) 以来,这始终为真。

来自 C11 标准:

The left operand of a comma operator is evaluated as a void expression [...]. Then the right operand is evaluated; the result has its type and value.

关于c - 使用逗号运算符的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32975449/

上一篇:C 编程 while 循环

下一篇:c - 数组的长度

相关文章:

c - 如何在 c 中成功创建一个 shell,当它后面跟着一个包含命令的文本文件时,它会解析该文件并执行命令?

c - STM32 SPI 未按预期工作

linux - 条件循环中的多个读取命令是否会在 shell 脚本中产生问题

c# - 如何从 robots.txt 文件中读取站点地图 url 文本

c - 包含 <limits.h> 后未定义 HOST_NAME_MAX

c - 从结构体定义的数组中打印出字符串

javascript - 我该如何做类似 "if (a > x > b)"的事情?

javascript - 如何重构这一堆 if 语句?

c - SHA1 哈希二进制 (20) 到字符串 (41)

Java min 查找器不工作