【问题标题】:GCC warning 'comparison is always true' when comparing the return of ntohs with a integer将 ntohs 的返回值与整数进行比较时,GCC 警告“比较始终为真”
【发布时间】:2017-09-14 18:03:44
【问题描述】:

我很难理解为什么在 Linux 上使用 GCC 4.8.4 时会收到此编译警告:

警告:由于数据类型[-Wtype-limits]的范围有限,比较总是正确的

比较这些值时:

uint16_t port_number = 23620;

if (ntohs(port_number) >= 0 && ntohs(port_number) <= 1023) {
    puts("The compiler warns that I will always end up here.");
} else {
    puts("Not reached");
}

我了解问题出在此比较中涉及的每个值所支持的最大大小。但是我怎样才能更好地理解并解决它呢?

【问题讨论】:

  • 只有&gt;= 0 会触发警告,因为uint16_t 是无符号的,因此总是非负数。
  • 在询问之前阅读函数的手册页总是一个好主意。
  • @Olaf 你能告诉我这个函数的手册页哪里有可以帮助我的信息吗?因为我没有找到任何与我的问题相关的有用信息......除了 uint16_t。
  • @HenriqueGouveia:编程就是为自己思考。这是 C 基础知识:unsigned 整数可以具有的最小值是多少?
  • @Olaf。抱歉,没找到。

标签: c gcc-warning


【解决方案1】:

ntohs 返回一个uint16_t。由于uint16_t 是无符号的,它总是大于或等于0。因此,ntohs(port_number) &gt;= 0 将始终解析为 true。这就是您收到警告的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    相关资源
    最近更新 更多