Although functions that return pointers are handled just like any other type of
function, a few important concepts need to be discussed.
Pointers to variables are neither integers nor unsigned integers. They are the
memory addresses of a certain type of data. The reason for this distinction is because
pointer arithmetic is relative to the base type. For example, if an integer pointer is
incremented, it will contain a value that is 4 greater than its previous value (assuming
4-byte integers). In general, each time a pointer is incremented (or decremented), it
points to the next (or previous) item of its type. Since the length of different data types
may differ, the compiler must know what type of data the pointer is pointing to. For
this reason, a function that returns a pointer must declare explicitly what type of
pointer it is returning. For example, you should not use a return type of int * to return
a char * pointer!
To return a pointer, a function must be declared as having a pointer return type.
For example, this function returns a pointer to the first occurrence of the character c
in string s:
/* Return pointer of first occurrence of c in s. */
char *match(char c, char *s)
{
while(c!=*s && *s) s++;
return(s);
}
If no match is found, a pointer to the null terminator is returned. Here is a short
program that uses match() :
#include <stdio.h>
char *match(char c, char *s); /* prototype */
int main(void)
{
char s[80], *p, ch;
gets(s);
ch = getchar();
p = match(ch, s);
if(*p) /* there is a match */
printf("%s ", p);
else
printf("No match found.");
return 0;
}
This program reads a string and then a character. If the character is in the string, the
program prints the string from the point of match. Otherwise, it prints No match found.
C C++ Source Codes, C C++ Practical examples ,C C++ tutorial ,Your best resource for Learning C and C++
Showing posts with label Returning. Show all posts
Showing posts with label Returning. Show all posts
Wednesday, September 29, 2010
Returning Values in C, C+
All functions, except those of type void, return a value. This value is specified by the
return statement. In C, if a non-void function does not explicitly return a value via a
return statement, then a garbage value is returned. In C++, a non-void function must
contain a return statement that returns a value. That is, in C++, if a function is specified
as returning a value, any return statement within it must have a value associated with
it. However, if execution reaches the end of a non-void function, then a garbage value
is returned. Although this condition is not a syntax error, it is still a fundamental error
and should be avoided.
As long as a function is not declared as void, you may use it as an operand in an
expression. Therefore, each of the following expressions is valid:
x = power(y);
if(max(x,y) > 100) printf("greater");
for(ch=getchar(); isdigit(ch); ) ... ;
As a general rule, a function cannot be the target of an assignment. A statement
such as swap(x,y) = 100; /* incorrect statement */
is wrong. The C/C++ compiler will flag it as an error and will not compile a program
that contains it. (As is discussed in Part Two, C++ allows some interesting exceptions
to this general rule, enabling some types of functions to occur on the left side of an
assignment.)
When you write programs, your functions generally will be of three types. The
first type is simply computational. These functions are specifically designed to
perform operations on their arguments and return a value based on that operation.
A computational function is a "pure" function. Examples are the standard library
functions sqrt() and sin() , which compute the square root and sine of their arguments.
The second type of function manipulates information and returns a value that
simply indicates the success or failure of that manipulation. An example is the library
function fclose() , which is used to close a file. If the close operation is successful, the
function returns 0; if the operation is unsuccessful, it returns EOF.
The last type of function has no explicit return value. In essence, the function is
strictly procedural and produces no value. An example is exit() , which terminates a
program. All functions that do not return values should be declared as returning type
void. By declaring a function as void, you keep it from being used in an expression,
thus preventing accidental misuse.
Sometimes, functions that really don't produce an interesting result return
something anyway. For example, printf() returns the number of characters written.
Yet it would be unusual to find a program that actually checked this. In other words,
although all functions, except those of type void, return values, you don't have to use
the return value for anything. A common question concerning function return values
is, "Don't I have to assign this value to some variable since a value is being returned?"
The answer is no. If there is no assignment specified, the return value is simply
discarded. Consider the following program, which uses the function mul() :
#include <stdio.h>
int mul(int a, int b);
int main(void)
{
int x, y, z;
x = 10; y = 20;
z = mul(x, y); /* 1 */
printf("%d", mul(x,y)); /* 2 */
mul(x, y); /* 3 */
return 0;
}
int mul(int a, int b)
{
return a*b;
}
In line 1, the return value of mul() is assigned to z. In line 2, the return value is not
actually assigned, but it is used by the printf() function. Finally, in line 3, the return
value is lost because it is neither assigned to another variable nor used as part of an
expression.
return statement. In C, if a non-void function does not explicitly return a value via a
return statement, then a garbage value is returned. In C++, a non-void function must
contain a return statement that returns a value. That is, in C++, if a function is specified
as returning a value, any return statement within it must have a value associated with
it. However, if execution reaches the end of a non-void function, then a garbage value
is returned. Although this condition is not a syntax error, it is still a fundamental error
and should be avoided.
As long as a function is not declared as void, you may use it as an operand in an
expression. Therefore, each of the following expressions is valid:
x = power(y);
if(max(x,y) > 100) printf("greater");
for(ch=getchar(); isdigit(ch); ) ... ;
As a general rule, a function cannot be the target of an assignment. A statement
such as swap(x,y) = 100; /* incorrect statement */
is wrong. The C/C++ compiler will flag it as an error and will not compile a program
that contains it. (As is discussed in Part Two, C++ allows some interesting exceptions
to this general rule, enabling some types of functions to occur on the left side of an
assignment.)
When you write programs, your functions generally will be of three types. The
first type is simply computational. These functions are specifically designed to
perform operations on their arguments and return a value based on that operation.
A computational function is a "pure" function. Examples are the standard library
functions sqrt() and sin() , which compute the square root and sine of their arguments.
The second type of function manipulates information and returns a value that
simply indicates the success or failure of that manipulation. An example is the library
function fclose() , which is used to close a file. If the close operation is successful, the
function returns 0; if the operation is unsuccessful, it returns EOF.
The last type of function has no explicit return value. In essence, the function is
strictly procedural and produces no value. An example is exit() , which terminates a
program. All functions that do not return values should be declared as returning type
void. By declaring a function as void, you keep it from being used in an expression,
thus preventing accidental misuse.
Sometimes, functions that really don't produce an interesting result return
something anyway. For example, printf() returns the number of characters written.
Yet it would be unusual to find a program that actually checked this. In other words,
although all functions, except those of type void, return values, you don't have to use
the return value for anything. A common question concerning function return values
is, "Don't I have to assign this value to some variable since a value is being returned?"
The answer is no. If there is no assignment specified, the return value is simply
discarded. Consider the following program, which uses the function mul() :
#include <stdio.h>
int mul(int a, int b);
int main(void)
{
int x, y, z;
x = 10; y = 20;
z = mul(x, y); /* 1 */
printf("%d", mul(x,y)); /* 2 */
mul(x, y); /* 3 */
return 0;
}
int mul(int a, int b)
{
return a*b;
}
In line 1, the return value of mul() is assigned to z. In line 2, the return value is not
actually assigned, but it is used by the printf() function. Finally, in line 3, the return
value is lost because it is neither assigned to another variable nor used as part of an
expression.
Returning from a Function in C, C++
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 */
}
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 */
}
Monday, September 27, 2010
Returning Pointers in C,C++
Although functions that return pointers are handled just like any other type of
function, a few important concepts need to be discussed.
Pointers to variables are neither integers nor unsigned integers. They are the
memory addresses of a certain type of data. The reason for this distinction is because
pointer arithmetic is relative to the base type. For example, if an integer pointer is
incremented, it will contain a value that is 4 greater than its previous value (assuming
4-byte integers). In general, each time a pointer is incremented (or decremented), it
points to the next (or previous) item of its type. Since the length of different data types
may differ, the compiler must know what type of data the pointer is pointing to. For
this reason, a function that returns a pointer must declare explicitly what type of
pointer it is returning. For example, you should not use a return type of int * to return
a char * pointer!
To return a pointer, a function must be declared as having a pointer return type.
For example, this function returns a pointer to the first occurrence of the character c
in string s:
/* Return pointer of first occurrence of c in s. */
char *match(char c, char *s)
{
while(c!=*s && *s) s++;
return(s);
}
If no match is found, a pointer to the null terminator is returned. Here is a short
program that uses match() :
#include <stdio.h>
char *match(char c, char *s); /* prototype */
int main(void)
{
char s[80], *p, ch;
gets(s);
ch = getchar();
p = match(ch, s);
if(*p) /* there is a match */
printf("%s ", p);
else
printf("No match found.");
return 0;
}
This program reads a string and then a character. If the character is in the string, the
program prints the string from the point of match. Otherwise, it prints No match found.
function, a few important concepts need to be discussed.
Pointers to variables are neither integers nor unsigned integers. They are the
memory addresses of a certain type of data. The reason for this distinction is because
pointer arithmetic is relative to the base type. For example, if an integer pointer is
incremented, it will contain a value that is 4 greater than its previous value (assuming
4-byte integers). In general, each time a pointer is incremented (or decremented), it
points to the next (or previous) item of its type. Since the length of different data types
may differ, the compiler must know what type of data the pointer is pointing to. For
this reason, a function that returns a pointer must declare explicitly what type of
pointer it is returning. For example, you should not use a return type of int * to return
a char * pointer!
To return a pointer, a function must be declared as having a pointer return type.
For example, this function returns a pointer to the first occurrence of the character c
in string s:
/* Return pointer of first occurrence of c in s. */
char *match(char c, char *s)
{
while(c!=*s && *s) s++;
return(s);
}
If no match is found, a pointer to the null terminator is returned. Here is a short
program that uses match() :
#include <stdio.h>
char *match(char c, char *s); /* prototype */
int main(void)
{
char s[80], *p, ch;
gets(s);
ch = getchar();
p = match(ch, s);
if(*p) /* there is a match */
printf("%s ", p);
else
printf("No match found.");
return 0;
}
This program reads a string and then a character. If the character is in the string, the
program prints the string from the point of match. Otherwise, it prints No match found.
Returning Values
All functions, except those of type void, return a value. This value is specified by the
return statement. In C, if a non-void function does not explicitly return a value via a
return statement, then a garbage value is returned. In C++, a non-void function must
contain a return statement that returns a value. That is, in C++, if a function is specified
as returning a value, any return statement within it must have a value associated with
it. However, if execution reaches the end of a non-void function, then a garbage value
is returned. Although this condition is not a syntax error, it is still a fundamental error
and should be avoided.
As long as a function is not declared as void, you may use it as an operand in an
expression. Therefore, each of the following expressions is valid:
x = power(y);
if(max(x,y) > 100) printf("greater");
for(ch=getchar(); isdigit(ch); ) ... ;
As a general rule, a function cannot be the target of an assignment. A statement
such as
return statement. In C, if a non-void function does not explicitly return a value via a
return statement, then a garbage value is returned. In C++, a non-void function must
contain a return statement that returns a value. That is, in C++, if a function is specified
as returning a value, any return statement within it must have a value associated with
it. However, if execution reaches the end of a non-void function, then a garbage value
is returned. Although this condition is not a syntax error, it is still a fundamental error
and should be avoided.
As long as a function is not declared as void, you may use it as an operand in an
expression. Therefore, each of the following expressions is valid:
x = power(y);
if(max(x,y) > 100) printf("greater");
for(ch=getchar(); isdigit(ch); ) ... ;
As a general rule, a function cannot be the target of an assignment. A statement
such as
swap(x,y) = 100; /* incorrect statement */
is wrong. The C/C++ compiler will flag it as an error and will not compile a program
that contains it. (As is discussed in Part Two, C++ allows some interesting exceptions
to this general rule, enabling some types of functions to occur on the left side of an
assignment.)
When you write programs, your functions generally will be of three types. The
first type is simply computational. These functions are specifically designed to
perform operations on their arguments and return a value based on that operation.
A computational function is a "pure" function. Examples are the standard library
functions sqrt() and sin() , which compute the square root and sine of their arguments.
The second type of function manipulates information and returns a value that
simply indicates the success or failure of that manipulation. An example is the library
function fclose() , which is used to close a file. If the close operation is successful, the
function returns 0; if the operation is unsuccessful, it returns EOF.
The last type of function has no explicit return value. In essence, the function is
strictly procedural and produces no value. An example is exit() , which terminates a
program. All functions that do not return values should be declared as returning type
void. By declaring a function as void, you keep it from being used in an expression,
thus preventing accidental misuse.
Sometimes, functions that really don't produce an interesting result return
something anyway. For example, printf() returns the number of characters written.
Yet it would be unusual to find a program that actually checked this. In other words,
although all functions, except those of type void, return values, you don't have to use
the return value for anything. A common question concerning function return values
is, "Don't I have to assign this value to some variable since a value is being returned?"
The answer is no. If there is no assignment specified, the return value is simply
discarded. Consider the following program, which uses the function mul() :
#include <stdio.h>
int mul(int a, int b);
int main(void)
{
int x, y, z;
x = 10; y = 20;
z = mul(x, y); /* 1 */
printf("%d", mul(x,y)); /* 2 */
mul(x, y); /* 3 */return 0;
}
int mul(int a, int b)
{
return a*b;
}
In line 1, the return value of mul() is assigned to z. In line 2, the return value is not
actually assigned, but it is used by the printf() function. Finally, in line 3, the return
value is lost because it is neither assigned to another variable nor used as part of an
expression.
is wrong. The C/C++ compiler will flag it as an error and will not compile a program
that contains it. (As is discussed in Part Two, C++ allows some interesting exceptions
to this general rule, enabling some types of functions to occur on the left side of an
assignment.)
When you write programs, your functions generally will be of three types. The
first type is simply computational. These functions are specifically designed to
perform operations on their arguments and return a value based on that operation.
A computational function is a "pure" function. Examples are the standard library
functions sqrt() and sin() , which compute the square root and sine of their arguments.
The second type of function manipulates information and returns a value that
simply indicates the success or failure of that manipulation. An example is the library
function fclose() , which is used to close a file. If the close operation is successful, the
function returns 0; if the operation is unsuccessful, it returns EOF.
The last type of function has no explicit return value. In essence, the function is
strictly procedural and produces no value. An example is exit() , which terminates a
program. All functions that do not return values should be declared as returning type
void. By declaring a function as void, you keep it from being used in an expression,
thus preventing accidental misuse.
Sometimes, functions that really don't produce an interesting result return
something anyway. For example, printf() returns the number of characters written.
Yet it would be unusual to find a program that actually checked this. In other words,
although all functions, except those of type void, return values, you don't have to use
the return value for anything. A common question concerning function return values
is, "Don't I have to assign this value to some variable since a value is being returned?"
The answer is no. If there is no assignment specified, the return value is simply
discarded. Consider the following program, which uses the function mul() :
#include <stdio.h>
int mul(int a, int b);
int main(void)
{
int x, y, z;
x = 10; y = 20;
z = mul(x, y); /* 1 */
printf("%d", mul(x,y)); /* 2 */
mul(x, y); /* 3 */return 0;
}
int mul(int a, int b)
{
return a*b;
}
In line 1, the return value of mul() is assigned to z. In line 2, the return value is not
actually assigned, but it is used by the printf() function. Finally, in line 3, the return
value is lost because it is neither assigned to another variable nor used as part of an
expression.
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.
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");
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 */
}
}
/* 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 */
}
Subscribe to:
Posts (Atom)