Koe*_*en 2 c addition operator-precedence compound-assignment relational-operators
我读了一些代码并且遇到了这个相当神秘的语法:
size_t count = 1;
char *s = "hello you";
char *last_word = "there";
count += last_word < (s + strlen(s) - 1); #line of interest
Run Code Online (Sandbox Code Playgroud)
不知何故,计数增加了.但我认为<运算符会返回true或false.这条线做什么?
根据运算符precedance表,<绑定高于+=运算符,因此您的代码基本上是
count += ( last_word < (s + strlen(s) - 1)) ;
Run Code Online (Sandbox Code Playgroud)
其中,(A < B)评估为0或1 注,所以,最后,它减少到
count += 0;
Run Code Online (Sandbox Code Playgroud)
要么
count += 1;
Run Code Online (Sandbox Code Playgroud)
注意:与"1或0"部分,引用C11,章节§6.5.8/ p6,关系运算符有关
如果指定的关系是,如果是,则 每个运算符
<(小于),>(大于),<=(小于或等于)和>=(大于或等于)将产生.107)结果有类型.1true0falseint