The return Statement. McGraw-Hill The Complete Reference Fourth Edition
જાહેરાત
જાહેરાત
C h a p t e r 6 : F u n c t i o n s
147
#include <stdio.h> int main(int argc, char *argv[])
{ int t, i; for(t=0; t<argc; ++t) { i = 0;
} while(argv[t][i]) { putchar(argv[t][i]);
++i;
} printf("\n");
} return 0;
Remember, the first index accesses the string, and the second index accesses the individual characters of the string.
Normally, you use argc and argv to get initial commands into your program. In theory, you can have up to 32,767 arguments, but most operating systems do not allow more than a few. You typically use these arguments to indicate a filename or an option.
Using command line arguments gives your program a professional appearance and facilitates its use in batch files.
When a program does not require command line parameters, it is common practice to explicitly declare main( ) as having no parameters. For C programs this is accomplished by using the void keyword in its parameter list. (This is the approach used by the programs in Part One of this book.) However, for C++ programs you may simply specify an empty parameter list. In C++, the use of void to indicate an empty parameter list is allowed, but redundant.
The names argc and argv are traditional but arbitrary. You may name these two parameters to main( ) anything you like. Also, some compilers may support additional arguments to main( ), so be sure to check your user's manual.
The return Statement
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.
148
C + + : T h e C o m p l e t e R e f e r e n c e
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)
{
C h a p t e r 6 : F u n c t i o n s
149 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 */
Returning Values
All functions, except those of type void, return a value. This value is specified by the
return
statement. In C89, if a non-void function does not explicitly return a value via a return statement, then a garbage value is returned. In C++ (and C99), 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 flaw 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); ) ... ;
150
C + + : T h e C o m p l e t e R e f e r e n c e
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;
C h a p t e r 6 : F u n c t i o n s
151 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 Pointers
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);
}
152
C + + : T h e C o m p l e t e R e f e r e n c e
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.
Functions of Type void
One of void's uses is to explicitly declare functions that do not return values. This prevents their use in any expression and helps avert accidental misuse. For example, the function print_vertical( ) prints its string argument vertically down the side of the screen. Since it returns no value, it is declared as void.
void print_vertical(char *str)
{ while(*str) printf("%c\n", *str++);
}
Here is an example that uses print_vertical( ).
#include <stdio.h>
ડાઉનલોડ કરો
જાહેરાત