Koen Koen - 1 year ago 57
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 Source

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;


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download