【问题标题】:c: What does this line do?c:这条线是做什么的?
【发布时间】:2017-01-29 09:00:26
【问题描述】:

我读了一些代码,发现了这个相当神秘的语法:

size_t count = 1;
char *s         = "hello you";
char *last_word = "there";

count += last_word < (s + strlen(s) - 1); #line of interest

Count 以某种方式递增。但我认为

【问题讨论】:

  • last_word &lt; (s + strlen(s) - 1); 计算结果为 1 或 0(真或假)
  • 请参阅here 了解有关将布尔值转换为 int 的一些讨论
  • @EuanSmith 这与这里有什么关系?关系运算符返回int 类型的结果。布尔值从何而来?
  • 当然你在 C 中是对的。我忘记了 C 没有原生布尔类型 - 在 C++ 和 C# 中花费了太长时间。

标签: c addition operator-precedence compound-assignment relational-operators


【解决方案1】:

根据operator precedance 表,&lt; 绑定高于+= 运算符,因此您的代码本质上是

 count += ( last_word < (s + strlen(s) - 1)) ;

其中,(A &lt; B) 的计算结果为 0 或 1 注意,因此,它最终归约为

count += 0;

count += 1;

注意: 与“10”部分相关,引用 C11,第 §6.5.8/p6 章,关系运营商

每个运算符&lt;(小于)、&gt;(大于)、&lt;=(小于或等于)和&gt;= (大于或等于)如果指定的关系是true0,则应产生1 false.107) 结果的类型为int

【讨论】:

    【解决方案2】:

    在 C 中,关系运算符总是产生 0 或 1。所以,这个语句

    count += last_word < (s + strlen(s) - 1); 
    

    根据比较结果将 0 或 1 添加到 count。它可以写成(和等价于):

    if (last_word < (s + strlen(s) - 1)) {
       count = count + 1;
    } else {
       count = count + 0;
    }
    

    else 部分是不必要的;添加用于解释目的。)

    C11(草案 N1548.pdf),关系运算符,§6.5.8, 6

    每个运算符(大于)、=(大于或等于)如果 指定的关系为真,如果为假,则为 0。 107) 结果有 输入整数。

    【讨论】:

      【解决方案3】:

      在 C 中有一个 stdbool.h 标头,它定义为 true 和 false。本质上,您可以将基本实现视为:

      #define bool int
      #define true 1
      #define false 0
      

      truefalse 分别定义为不为零和等于零。所以基本上当last_word &lt; (s + strlen(s) - 1) 时,count 会加一。

      【讨论】:

      • 惊喜!! C 有布尔值。
      • @SouravGhosh 你的意思是stdbool 标头吗?
      • 是的,当然。 :)
      • 从 C99 开始还有一个 _Bool 类型,您可以在不使用 stdbool 标头的情况下使用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 2017-12-08
      • 2016-01-27
      • 2012-05-04
      • 1970-01-01
      相关资源
      最近更新 更多