K&R2 section 4.1 example

A

arnuld

This is the example from section 4.1 of K&R2,page 69 in my book:


int str_index( char s[], char p[] )
{
int i, j, k;

for( i = 0; s != '\0'; ++i )
{
for( k = 0, j = i; ( (p[k] != '\0') && (s[j] == p[k]) ); ++k, ++j )
;

if( (k > 0) && p[k] == '\0' )
{
return i;
}
}

return -1;
}




Since I feel lots of difficulty with code from K&R2, I alongside also read
Steve's K&R2 notes. From here:

http://www.eskimo.com/~scs/cclass/krnotes/sx7a.html


I see that Steve says the "k > 0" test in last "if" statement is not
essential. I removed that from K&R2's original example and the program is
running fine without any semantic-bug at all.

I want to know why K&R put thay "k > 0" there ? what's its importance ?
 
H

Hallvard B Furuseth

arnuld said:
This is the example from section 4.1 of K&R2,page 69 in my book:
int str_index( char s[], char p[] )
{
int i, j, k;

for( i = 0; s != '\0'; ++i )
{
for( k = 0, j = i; ( (p[k] != '\0') && (s[j] == p[k]) ); ++k, ++j )
;

if( (k > 0) && p[k] == '\0' )
{
return i;
}
}

return -1;
}


(...)
I want to know why K&R put thay "k > 0" there ? what's its importance ?


Well, look at the if-test: The branch can only be taken if p[k] == '\0',
so the k>0 test only eliminates the (k == 0 && p[k] == '\0') case, i.e.
p is "". If p = "", then with the k>0 test the function always returns
-1 (after iterating through s). Without the test it returns 0 when s is
not empty.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top