Thread: Recursive function problem

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    5

    Recursive function problem

    Hey guys I'm new here, I have a problem with this function, can anyone tell me what's wrong?

    Code:
    int rec (char *s, char c);
    
    int main()
    {
    	char s[10]="abra";
    	char c='a';
    	printf ("%c appeared %d times\n",c,rec(s,c));
    	return 0;
    }
    
    
    int rec (char *s, char c)
    {
    
    	if (*s=='\0')
    		return;
    	
    	if (c==*s)
    	{
    		return (1 + rec(s+1,c));
    	}
    
    	else
    	{
    		return rec(s+1,c);
    	}
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You should not be allowed to return; from an int function. You need to return an actual int.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    5
    Thanks a lot. worked like a charm.

  4. #4
    Banned
    Join Date
    Jan 2009
    Posts
    30
    Just for the sake of personal curiosity, did your compiler issue any sort of warning when you had return; in your code?

  5. #5
    Registered User
    Join Date
    Jan 2009
    Posts
    5
    sphynxter I just saw your post.

    VS2008 did issue a warning yet by being so annoyed by the fact that the program did not work I didn't know what to do with it.

    warning C4033: 'rec' must return a value
    warning C4715: 'rec' : not all control paths return a value

  6. #6
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by trnd View Post
    I didn't know what to do with it.

    warning C4033: 'rec' must return a value
    warning C4715: 'rec' : not all control paths return a value
    instead of this
    Code:
    else
    	{
    		return rec(s+1,c);
    	}
    do simply
    Code:
    	return rec(s+1,c);
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. recursive function problem
    By jk81 in forum C Programming
    Replies: 2
    Last Post: 10-25-2002, 06:02 AM