Thread: Any error in this function?

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    10

    Any error in this function?

    I'm self studying C with Practical C programming (3:rd) - O'Reilly.

    I have the following exercise
    "Exercise 9-2 : Write a function begins(string1,string2) that returns true if string1 begins string2. Write a program to test the function."

    I write the following code to do it! Is this a correct and good code?
    Code:
    #include <stdio.h>
    
    int begins(char str1[], char str2[])
    {
    	int i, state;
    	
    	for(i=0 ; str1[i] != '\0' ; i++)
    	{
    		if(str1[i] == str2[i])
    		{
    		state = 1;
    		}
    		else
    		{
    		state = 0;
    		break;
    		}
    		
    	}
    	return(state);
    }
    
    int main()
    {
    	printf("True : %i\n", begins("123", "12345"));
    	printf("False : %i\n", begins("1234", "122345"));
    
    	return(0);
    }
    I have the feeling that I could do this in another and better way for some reason.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Of course you can do it in different ways... some better some not...

    So, go for it... experiment, find out what does and doesn't work... that's how you learn.

    Code:
    // does str1 begin with str2?  (1 = yes, 0 = no)
    int Begins(char *str1, char *str2)
      { int idx = strlen(str2);
         while (--idx > -1)
            if (str1[idx] != str2[idx]
              return 0; 
         return 1; }
    Last edited by CommonTater; 09-09-2011 at 05:26 AM.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    And what do you get for
    Code:
    begins("False", "abcdef");
    begins("False", "F");
    The trick is to look at your code and ask yourself "How can I break this?"

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    There are lots of ways to do the same thing in C. Going off of what you have:
    Code:
    for( i = 0; str1[ i ]; i++ )
        if( str1[ i ] != str2[ i ] )
            break;
    return str1[ i ] == '\0';

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Error "in function 'main' syntax error before 'int' Help Please
    By blackhat11907 in forum C Programming
    Replies: 5
    Last Post: 08-20-2011, 07:05 PM
  2. Replies: 8
    Last Post: 07-08-2011, 01:16 PM
  3. c function error
    By crocker in forum C Programming
    Replies: 12
    Last Post: 12-23-2009, 10:31 AM
  4. Error: _ defined as a function returning a function?
    By Jardon in forum C Programming
    Replies: 15
    Last Post: 07-29-2009, 11:53 AM
  5. function calling within another function error
    By bazzano in forum C Programming
    Replies: 2
    Last Post: 03-11-2006, 01:40 AM