Posted on 31st October 20092 Responses
Returning from a Function in C and C++

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
#include
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
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 */
}

Popularity: 1% [?]

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • BarraPunto
  • Bitacoras.com
  • BlinkList
  • blogmarks
  • BlogMemes Fr
  • BlogMemes Sp
  • Blogosphere News
  • blogtercimlap
  • co.mments
  • connotea
  • Current
  • Design Float
  • Diigo
  • DotNetKicks
  • DZone
  • eKudos
  • email
Comments
comment by mmsgfricdiw
Posted on December 13, 2009 at 6:38 am

is it mandatory that we use this function in programming..??

comment by Nixon
Posted on December 13, 2009 at 6:43 am

nice article and nice site

Leave a Response