tags:

views:

82

answers:

2

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?

+4  A: 

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.

Chris Schmich
Ahh you mean its going to say that the peice of code below return value never proceeds
fahad
Correct, `return 0;` will never be executed.
Chris Schmich
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.
Chris Schmich
+1  A: 

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.

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