of course needle
and haystack
both are pointers and thus they both store addresses which are essentially numbers so we can perform arithmetic operations on them.
needle - haystack + 2 + 1
subtracts the address that haystack
stores from the address that needle
stores (not the other way around) then adds 3.
now what is that and why is it done that way?
in the distribution code (above the referenced statement), you'll find a statement like this
char* needle = strstr(haystack, "\r\n");
according to the man page for strstr
, it finds the first occurrence of its second argument (which is a string) in its first argument (which is also a string) and returns a pointer the beginning of that occurrence.
in other words, this finds "\r\n"
in haystack
and returns a pointer to it.
so if haystack
stores 100 and the first occurrence of "\r\n"
is at 110, strstr
will return 110.
this tells you that needle - haystack
just calculates the length of the string from the beginning of haystack
to the letter before right before the first occurrence of "\r\n"
(excluding the "\r\n"
of course).
why adding 2?
to make room for "\r\n"
why adding 1?
to make room for the null character '\0'
to terminate the string line
.
why is it calculated that way?
technically this is faster and more efficient as oppose to using a function like strlen
to calculate the length of haystack
.
strlen
would count the characters one by one which would take n steps where n is the length of the string.
this is a constant time operation. all what is done is a subtraction operation, and 2 additions and that's always the case.
however, recall that to do that we needed to find the "\r\n"
(through the call to strstr
) which I suppose takes n steps. we also assumed that there's nothing after the "\r\n"
in haystack
.
couldn't we just add 3 instead of 2 + 1?
we could, but I guess they made it that way to make it relatively easier to understand.