📄 chapter03.html
字号:
new functions. Actually, there are a lot of reasons, but this example only demonstrates two:<OL> <LI>Creating a new function gives you an opportunity to give a name to a group of statements. Functions can simplify a program by hiding a complex computation behind a single command, and by using English words in place of arcane code. Which is clearer, <TT>newLine</TT> or <TT>cout << endl</TT>? </P></LI> <LI>Creating a new function can make a program smaller by eliminating repetitive code. For example, a short way to print nine consecutive new lines is to call <TT>threeLine</TT> three times. How would you print 27 new lines?</LI></OL><BR><BR><H3>3.6 Definitions and uses</H3><P>Pulling together all the code fragments from the previous section, the whole program looks like this:</P><PRE>#include <iostream.h>void newLine (){ cout << endl;}void threeLine (){ newLine (); newLine (); newLine ();}void main (){ cout << "First Line." << endl; threeLine (); cout << "Second Line." << endl;}</PRE><P>This program contains three function definitions: <TT>newLine</TT>, <TT>threeLine</TT>, and <TT>main</TT>. Inside the definition of <TT>main</TT>,there is a statement that uses or calls <TT>threeLine</TT>. Similarly, <TT>threeLine</TT> calls <TT>newLine</TT> three times. Notice that the definition of each function appears above the place where it is used.</P><P>This is necessary in C++; the definition of a function must appear before (above) the first use of the function. You should try compiling this program with the functions in a different order and see what error messages you get.</P><BR><BR><H3>3.7 Programs with multiple functions</H3><P>When you look at a class definition that contains several functions, it is tempting to read it from top to bottom, but that is likely to be confusing, because that is not the <B>order of execution</B> of the program.</P><P>Execution always begins at the first statement of <TT>main</TT>, regardless of where it is in the program (often it is at the bottom). Statements are executed one at a time, in order, until you reach a function call. Function calls are like a detour in the flow of execution. Instead of going to the next statement, you go to the first line of the called function, execute all the statements there, and then come back and pick up again where you left off.</P><P>That sounds simple enough, except that you have to remember that one function can call another. Thus, while we are in the middle of <TT>main</TT>,we might have to go off and execute the statements in <TT>threeLine</TT>. But while we are executing <TT>threeLine</TT>, we get interrupted three times to go off and execute <TT>newLine</TT>.</P><P>Fortunately, C++ is adept at keeping track of where it is, so each time <TT>newLine</TT> completes, the program picks up where it left off in <TT>threeLine</TT>, and eventually gets back to <TT>main</TT> so the program can terminate.</P><P>What's the moral of this sordid tale? When you read a program, don't read from top to bottom. Instead, follow the flow of execution.</P><BR><BR><H3>3.8 Parameters and arguments</H3><P>Some of the built-in functions we have used have <B>parameters</B>, which are values that you provide to let the function do its job. For example, if you want to find the sine of a number, you have to indicate what the number is.Thus, <TT>sin</TT> takes a <TT>double</TT> value as a parameter.</P><P>Some functions take more than one parameter, like <TT>pow</TT>, which takes two <TT>doubles</TT>, the base and the exponent.</P><P>Notice that in each of these cases we have to specify not only how many parameters there are, but also what type they are. So it shouldn't surprise you that when you write a class definition, the parameter list indicates the type of each parameter. For example:</P><PRE> void printTwice (char phil) { cout << phil << phil << endl; }</PRE><P>This function takes a single parameter, named <TT>phil</TT>, that has type <TT>char</TT>. Whatever that parameter is (and at this point we have no idea what it is), it gets printed twice, followed by a newline. I chose the name <TT>phil</TT> to suggest that the name you give a parameter is up to you, but in general you want to choose something more illustrative than <TT>phil</TT>.</P><P>In order to call this function, we have to provide a <TT>char</TT>. For example, we might have a <TT>main</TT> function like this:</P><PRE> void main () { printTwice ('a'); }</PRE><P>The <TT>char</TT> value you provide is called an <B>argument</TT>, and we say that the argument is <B>passed</B> to the function. In this case the value<TT>'a'</TT> is passed as an argument to <TT>printTwice</TT> where it will get printed twice.</P><P>Alternatively, if we had a <TT>char</TT> variable, we could use it as an argument instead:</P><PRE> void main () { char argument = 'b'; printTwice (argument); }</PRE><P>Notice something very important here: the name of the variable we passas an argument (<TT>argument</TT>) has nothing to do with the name of theparameter (<TT>phil</TT>). Let me say that again:</P><BLOCKQUOTE><B>The name of the variable we pass as an argument has nothing to dowith the name of the parameter.</B></BLOCKQUOTE><P>They can be the same or they can be different, but it is important to realize that they are not the same thing, except that they happen to have the same value (in this case the character <TT>'b'</TT>).</P><P>The value you provide as an argument must have the same type as the parameter of the function you call. This rule is important, but it is sometimes confusing because C++ sometimes converts arguments from one type to another automatically. For now you should learn the general rule, and we will deal with exceptions later.</P><BR><BR><H3>3.9 Parameters and variables are local</H3><P>Parameters and variables only exist inside their own functions. Within theconfines of <TT>main</TT>, there is no such thing as <TT>phil</TT>. If you try to use it, the compiler will complain. Similarly, inside <TT>printTwice</TT> there is no such thing as <TT>argument</TT>.</P><P>Variables like this are said to be <B>local</B>. In order to keep track of parameters and local variables, it is useful to draw a <B>stack diagram</B>.Like state diagrams, stack diagrams show the value of each variable, but the variables are contained in larger boxes that indicate which function they belong to.</P><P>For example, the state diagram for <TT>printTwice</TT> looks like this:</P><P CLASS=1><IMG SRC="images/stack.png" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/stack.png" ALT="Stack Image"></P><P>Whenever a function is called, it creates a new <B>instance</B> of that function. Each instance of a function contains the parameters and local variables for that function. In the diagram an instance of a function is represented by a box with the name of the function on the outside and the variables and parameters inside.</P><P>In the example, <TT>main</TT> has one local variable, <TT>argument</TT>, andno parameters. <TT>printTwice</TT> has no local variables and one parameter, named <TT>phil</TT>.</P><BR><BR><H3>3.10 Functions with multiple parameters</H3><P>The syntax for declaring and invoking functions with multiple parameters is a common source of errors. First, remember that you have to declare the type of every parameter. For example</P><PRE> void printTime (int hour, int minute) { cout << hour; cout << ":"; cout << minute; }</PRE><P>It might be tempting to write <TT>(int hour, minute)</TT>, but that format is only legal for variable declarations, not for parameters.</P><P>Another common source of confusion is that you do not have to declare the types of arguments. The following is wrong!</P><PRE> int hour = 11; int minute = 59; printTime (int hour, int minute); // WRONG!</PRE><P>In this case, the compiler can tell the type of <TT>hour</TT> and <TT>minute</TT> by looking at their declarations. It is unnecessary and illegal to include the type when you pass them as arguments. The correctsyntax is <TT>printTime (hour, minute)</TT>.</P><BR><BR><H3>3.11 Functions with results</H3><P>You might have noticed by now that some of the functions we are using, like the math functions, yield results. Other functions, like <TT>newLine</TT>, perform an action but don't return a value. That raises some questions:</P><OL> <LI>What happens if you call a function and you don't do anything with the result (i.e. you don't assign it to a variable or use it as part of a larger expression)?</LI> <LI>What happens if you use a function without a result as part of an expression, like <TT>newLine() + 7</TT>?</LI> <LI>Can we write functions that yield results, or are we stuck with things like <TT>newLine</TT> and <TT>printTwice</TT>?</LI></OL><P>The answer to the third question is ``yes, you can write functions thatreturn values,'' and we'll do it in a couple of chapters. I will leave it up to you to answer the other two questions by trying them out. Any time you have a question about what is legal or illegal in C++, a good way to find out is to ask the compiler.</P><BR><BR><H3>3.12 Glossary</H3><DL> <DT>floating-point:</DT><DD> A type of variable (or value) that can contain fractions as well as integers. There are a few floating-point types in C++; the one we use in this book is <TT>double</TT>.</DD> <DT>initialization:</DT><DD> A statement that declares a new variable and assigns a value to it at the same time.</DD> <DT>function:</DT><DD> A named sequence of statements that performs some useful function. Functions may or may not take parameters, and may or may not produce a result.</DD> <DT>parameter:</DT><DD> A piece of information you provide in order to call a function. Parameters are like variables in the sense that they contain values and have types.</DD> <DT>argument:</DT><DD> A value that you provide when you call a function. This value must have the same type as the corresponding parameter.</DD> <DT>call:</DT><DD> Cause a function to be executed.</DD></DL><BR><DIV CLASS=navigation><HR> <TABLE ALIGN=center WIDTH="100%" CELLPADDING=0 CELLSPACING=2> <TR> <TD><A HREF="chapter04.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter04.html"> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="next" SRC="images/next.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/next.gif"></A> </TD> <TD><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html"> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="up" SRC="images/up.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/up.gif"></A> </TD> <TD><A HREF="chapter02.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter02.html"> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="previous" SRC="images/previous.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/previous.gif"></A> </TD> <TD ALIGN=center BGCOLOR="#99CCFF" WIDTH="100%"> <B CLASS=title>How to Think Like a Computer Scientist: Chapter 3</B> </TD> <TD><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html"> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="contents" SRC="images/contents.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/contents.gif"></A> </TD> <TD> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="" SRC="images/blank.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/blank.gif"> </TD> <TD> <IMG WIDTH=32 HEIGHT=32 ALIGN=bottom BORDER=0 ALT="" SRC="images/blank.gif" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/images/blank.gif"> </TD> </TR> </TABLE> <B CLASS=navlabel>Next:</B> <SPAN CLASS=sectref><A HREF="chapter04.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter04.html">Chapter 4</A></SPAN> <B CLASS=navlabel>Up:</B> <SPAN CLASS=sectref><A HREF="index.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/index.html">Index</A></SPAN> <B CLASS=navlabel>Previous:</B> <SPAN CLASS=sectref><A HREF="chapter02.html" tppabs="http://rocky.wellesley.edu/downey/ost/thinkCS/c++_html/chapter02.html">Chapter 2</A></SPAN> <HR></DIV></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -