K&R2 section 4.1 example

Discussion in 'C Programming' started by arnuld, Apr 3, 2008.

  1. arnuld

    arnuld Guest

    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 ?
    arnuld, Apr 3, 2008
    #1
    1. Advertising

  2. arnuld writes:
    > 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.

    --
    Hallvard
    Hallvard B Furuseth, Apr 3, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Porky Pig Jr
    Replies:
    5
    Views:
    411
    Porky Pig Jr
    May 3, 2004
  2. arnuld
    Replies:
    7
    Views:
    357
    Salt_Peter
    Oct 30, 2006
  3. arnuld
    Replies:
    1
    Views:
    314
    Marcus Kwok
    Jul 13, 2007
  4. arnuld
    Replies:
    7
    Views:
    936
    Joachim Schmitz
    Apr 5, 2008
  5. kampy
    Replies:
    9
    Views:
    314
    Steven D'Aprano
    Oct 19, 2012
Loading...

Share This Page