2

I read some code and came over this rather cryptic syntax:

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

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

Count is incremented, somehow. But I thought the < operator would return true or false. What does this line do?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Koen
  • 110
  • 1
  • 11
  • 2
    `last_word < (s + strlen(s) - 1);` evaluates to either 1 or 0 (true or false) – Linus Sep 21 '16 at 08:14
  • see [here](http://stackoverflow.com/questions/2725044/can-i-assume-booltrue-int1-for-any-c-compiler) for some discussion about casting boolean to int – Euan Smith Sep 21 '16 at 08:19
  • @EuanSmith how is that relevant here? relational operators return the result of type `int`. From where boolean comes into picture? – Sourav Ghosh Sep 21 '16 at 08:36
  • Of course you are right in C. I had forgotten that C does not have a native boolean type - spent too long in C++ and C#. – Euan Smith Sep 21 '16 at 10:15

3 Answers3

5

As per the operator precedance table, < binds higher than += operator, so your code is essentially

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

where, the (A < B) evaluates to either 0 or 1 Note, so, finally, it reduces to

count += 0;

or

count += 1;

Note: related to the "1 or 0" part, quoting C11, chapter §6.5.8/p6, Relational operators

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

In C, relational operators always yield 0 or 1. So, this statement

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

adds either 0 or 1 to count depending on the comparison's result. It can be written as (and equivalent to):

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

(The else part is needless; added for explanatory purpose.)

C11 (draft N1548.pdf), Relational operators, §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.

P.P
  • 117,907
  • 20
  • 175
  • 238
0

In C there is a the stdbool.h header which defines as true and false. Essentially you can think of the basic implemantation as:

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

true and false are defined as not zero and equal to zero respectively. So basically when last_word < (s + strlen(s) - 1), count is incremented by one.

Linus
  • 1,516
  • 17
  • 35