c:这条线是做什么的?

c: What does this line do?

我阅读了一些代码并了解了这个相当神秘的语法:

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

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

计数以某种方式递增。但我认为 < 运算符会 return 真或假。 这条线是做什么的?

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

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

其中,(A < B) 的计算结果为 0 或 1 ,因此,最后,它减少为

count += 0;

count += 1;

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

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.107) The result has type int.

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

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

truefalse分别定义为不为零和等于零。所以基本上当last_word < (s + strlen(s) - 1)时,计数加一。

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

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

根据比较结果向 count 添加 0 或 1。它可以写成(并且等同于):

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

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

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

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. 107) The result has type int.