Recursive function problem

This is a discussion on Recursive function problem within the C Programming forums, part of the General Programming Boards category; Hey guys I'm new here, I have a problem with this function, can anyone tell me what's wrong? Code: int ...

  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,185
    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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    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);
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

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, 02: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21