Monday, September 27, 2010

The return Statement : Returning from a Function

The return statement itself is described in Chapter 3. As explained, it has two important
uses. First, it causes an immediate exit from the function that it is in. That is, it causes
program execution to return to the calling code. Second, it may be used to return a
value. This section examines how the return statement is used.

Returning from a Function
There are two ways that a function terminates execution and returns to the caller. The
first occurs when the last statement in the function has executed and, conceptually,
the function's ending curly brace (}) is encountered. (Of course, the curly brace isn't
actually present in the object code, but you can think of it in this way.) For example, the
pr_reverse() function in this program simply prints the string "I like C++" backwards
on the screen and then returns.
#include <string.h>
#include <stdio.h>
void pr_reverse(char *s);
int main(void)
{
pr_reverse("I like C++");
return 0;
}
void pr_reverse(char *s)
{
register int t;
for(t=strlen(s)-1; t>=0; t--) putchar(s[t]);
}
Once the string has been displayed, there is nothing left for pr_reverse() to do, so it
returns to the place from which it was called.
Actually, not many functions use this default method of terminating their
execution. Most functions rely on the return statement to stop execution either
because a value must be returned or to make a function's code simpler and more
efficient.
A function may contain several return statements. For example, the find_substr()
function in the following program returns the starting position of a substring within
a string, or returns −1 if no match is found.
#include <stdio.h>
int find_substr(char *s1, char *s2);
int main(void)
{
if(find_substr("C++ is fun", "is") != -1)
printf("substring is found");

return 0;
}
/* Return index of first match of s2 in s1. */
int find_substr(char *s1, char *s2)
{
register int t;
char *p, *p2;
for(t=0; s1[t]; t++) {
p = &s1[t];
p2 = s2;
while(*p2 && *p2==*p) {
p++;
p2++;
}
if(!*p2) return t; /* 1st return */
}
return -1; /* 2nd return */
}

No comments:

Post a Comment