I'm self-teaching myself C with a complete reference book. Unfortunately that means that the author assumes that the reader is familiar with fundamental concepts and doesn't bother commenting the code. Here is an unnecessarily obfuscated code excerpt demonstrating "the use of return statements" along with my attempt to understand what is going on. Please list any corrections.
int find_ substr( char *s1, char *s2)
{
register int t;
char *p, *p2;
for( t= 0; s1[ t]; t++) {
p = &s1[ t];
p2 = s2;
while(* p2 && *p2==* p) {
p++;
p2++;
}
if(!* p2) return t; /* substring was found */
}
return -1; /* substring not found */
}
So pointers s1 and s2 are passed into "find substring." s2 is the substring we are searching for and s1 is the string we are searching through. As the function cycles through each character of p (equivalent to s1) the letters are compared to p2. When a letter match is found, the while loop checks for a complete match. (ie: you might be searching for digging but you only find dig. If that happens the orange statement is false and we're back at the for loop) If there is a complete match, p2 (the string we're searching through) is finite, the pointer arithmetic goes out of bounds and null is returned, bringing you out of the loop and into the for. The pointer p2 is still out of pounds and the if statement evaluates to false, but the ! changes this to true so t is returned. If the substring is not in the string we are searching through, the while and for loops exits and the -1 is returned.
One statement that confuses me in particular is the loop condition in
for( t= 0; s1[ t]; t++)
Does this cycle through every element of any array? What happens if one of your elements happens to have a value of 0? will you break out of the loop or does it continue on until you are out of bounds and returns null? Since there is no bounds checking in C, the compiler will not stop you from writing more elements than allocated at the risk of overwriting other memory, is it possible that the memory cells wlil be contiguous and maybe you will continue looping past the 'last' element of the array?