You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言三元运算符输出不符合预期的问题咨询

问题分析:为什么输出是3而不是5?

先看你的代码:

void main() {
   char *x = "abc";
   char *y = "defgh";
   unsigned int c=0;
   int len = ((strlen(x) - strlen(y)) > c) ? strlen(x) : strlen(y);
   printf("%d\n", len);
}

问题出在无符号整数的运算特性上:

  • strlen()函数的返回值类型是size_t,这是一个无符号整数类型。
  • 当你计算strlen(x) - strlen(y)时,本质是无符号数3减无符号数5。无符号数没有负数,运算溢出时会按模2^N(N是系统中size_t的位数)绕回,结果会变成一个非常大的正整数(比如32位系统下是4294967294)。
  • 这个大的无符号数和unsigned int类型的c=0比较时,显然大于0,所以三元运算符的条件为真,最终取strlen(x)的值3,输出就是3。

如果想得到预期的5,需要先把strlen的结果转换成有符号整数再做减法:

int len = (( (int)strlen(x) - (int)strlen(y) ) > c) ? strlen(x) : strlen(y);

内容的提问来源于stack exchange,提问作者taurus05

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:15:48