1

If I make a function that returns more than 1 values to the same variable like in the example:

char *strstr(char *s1,char *s2)
{
 int flag=1;
 char i,j;
 for(i=0;*s1;i++)
 {
  if(s1[i]==s2[0])
  for(j=i;*s2;j++)
  {
   if(s1[j]!=s2[j])
   flag=0;
  }

 }
 return i;
 return 0;
}

What will be the actual value returned by the function?Will the last returned value overlap the first returned value?

3
  • 3
    return exits a function. So return 0; won't ever be executed. Commented Aug 28, 2010 at 7:19
  • @trinithis:Thanks for the info :D.. Commented Aug 28, 2010 at 7:22
  • 1
    Compiler might even warn you 'unreachable statement'. Commented Aug 28, 2010 at 9:19

2 Answers 2

4

The first return hit (return i; here) will be what is actually returned. A good compiler will tell you that the return 0; is dead code since it is unreachable (i.e. there is no way for control flow to reach that statement).

Unless you create your own tuple or pair structure (or some other more semantic structure), the only reasonable way to return multiple values (without using globals or something else unmaintainable) in C is to do it with pointers as out parameters, though you say you don't want to do this.

Sign up to request clarification or add additional context in comments.

3 Comments

Ahh you mean its going to say that the peice of code below return value never proceeds
Correct, return 0; will never be executed.
Also, please see Praveen's answer below. Saying that code below a return doesn't execute is inaccurate. The more accurate statement is that when a return is reached, control flow is returned back to the calling function. In your case, however, this means that return i; terminates that method, so return 0; never executes.
1

Programs usually tend to have multiple return statements, which however doesn't mean code below first return wont be executed. This is usually how a function is designed to return error codes if there is one. Small example is as follows:

char * foo() 
{
char *ptr;
ptr=malloc(256);
if(ptr==NULL)
return NULL;   /// First return statement is here 
strcpy(ptr,"Stackoverflow");
return ptr; // This is second return statement.
}

Also this does not mean both with be executed in a single call. Only one return is executed. And the function returns to the point of its call.

1 Comment

You should not use numbers like 256 in your code =p.Thanks =D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.