Reputation:
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?
Upvotes: 1
Views: 685
Reputation: 10393
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.
Upvotes: 1
Reputation: 29476
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.
Upvotes: 4