Koen Koen - 2 months ago 6
C Question

c: What does this line do?

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?

Answer

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.