⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch05.htm

📁 vc的电子书
💻 HTM
📖 第 1 页 / 共 5 页
字号:
it consists of only one statement, as in this case.
<H4 ALIGN="CENTER"><A NAME="Heading11"></A><FONT COLOR="#000077">Defining the Function</FONT></H4>
<P>The definition of a function consists of the function header and its body. The
header is exactly like the function prototype, except that the parameters must be
named, and there is no terminating semicolon.</P>
<P>The body of the function is a set of statements enclosed in braces. Figure 5.3
shows the header and body of a function.</P>
<P><A NAME="Heading12"></A><A HREF="05zcp03.jpg" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/art/ch05/05zcp03.jpg"><FONT COLOR="#000077">Figure
5.3.</FONT></A><FONT COLOR="#000077"> </FONT><I>The header and body of a function.</I>
<H3 ALIGN="CENTER"><A NAME="Heading13"></A><FONT COLOR="#000077">Functions</FONT></H3>
<P>Function Prototype Syntax</P>
<PRE><FONT COLOR="#0066FF">return_type function_name ( [type [parameterName]]...);
</FONT></PRE>
<P>Function Definition Syntax</P>
<PRE><FONT COLOR="#0066FF">return_type function_name ( [type parameterName]...)
{
    statements;
}
</FONT></PRE>
<P>A function prototype tells the compiler the return type, name, and parameter list.
Func-tions are not required to have parameters, and if they do, the prototype is
not required to list their names, only their types. A prototype always ends with
a semicolon (;). A function definition must agree in return type and parameter list
with its prototype. It must provide names for all the parameters, and the body of
the function definition must be surrounded by braces. All statements within the body
of the function must be terminated with semicolons, but the function itself is not
ended with a semicolon; it ends with a closing brace. If the function returns a value,
it should end with a <TT>return</TT> statement, although <TT>return</TT> statements
can legally appear anywhere in the body of the function. Every function has a return
type. If one is not explicitly designated, the return type will be <TT>int</TT>.
Be sure to give every function an explicit return type. If a function does not return
a value, its return type will be <TT>void</TT>.
<H4>
<HR>
<FONT COLOR="#000077">Function Prototype Examples</FONT></H4>
<PRE><FONT COLOR="#0066FF">long FindArea(long length, long width); // returns long, has two parameters
void PrintMessage(int messageNumber); // returns void, has one parameter
int GetChoice();                      // returns int, has no parameters
</FONT></PRE>
<PRE><FONT COLOR="#0066FF">
BadFunction();                        // returns int, has no parameters
</FONT></PRE>
<P>
<HR>
<FONT COLOR="#000077"><B><BR>
<BR>
</B></FONT>
<HR>
<FONT COLOR="#000077"><B>Function Definition Examples</B></FONT></P>
<PRE><FONT COLOR="#0066FF">long Area(long l, long w)
{
     return l * w;
}

void PrintMessage(int whichMsg)
{
     if (whichMsg == 0)
          cout &lt;&lt; &quot;Hello.\n&quot;;
     if (whichMsg == 1)
          cout &lt;&lt; &quot;Goodbye.\n&quot;;
     if (whichMsg &gt; 1)
          cout &lt;&lt; &quot;I'm confused.\n&quot;;
}</FONT></PRE>
<P>
<HR>
</P>
<PRE></PRE>
<H3 ALIGN="CENTER"><A NAME="Heading14"></A><FONT COLOR="#000077">Execution of Functions</FONT></H3>
<P>When you call a function, execution begins with the first statement after the
opening brace (<TT>{</TT>). Branching can be accomplished by using the <TT>if</TT>
statement (and related statements that will be discussed on Day 7, &quot;More Program
Flow&quot;). Functions can also call other functions and can even call themselves
(see the section &quot;Recursion,&quot; later in this chapter).
<H3 ALIGN="CENTER"><A NAME="Heading15"></A><FONT COLOR="#000077">Local Variables</FONT></H3>
<P>Not only can you pass in variables to the function, but you also can declare variables
within the body of the function. This is done using local variables, so named because
they exist only locally within the function itself. When the function returns, the
local variables are no longer available.</P>
<P>Local variables are defined like any other variables. The parameters passed in
to the function are also considered local variables and can be used exactly as if
they had been defined within the body of the function. Listing 5.2 is an example
of using parameters and locally defined variables within a function.</P>
<P><A NAME="Heading16"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 5.2. The use
of local variables and parameters.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">1:     #include &lt;iostream.h&gt;
2:
3:     float Convert(float);
4:     int main()
5:     {
6:        float TempFer;
7:        float TempCel;
8:
9:        cout &lt;&lt; &quot;Please enter the temperature in Fahrenheit: &quot;;
10:       cin &gt;&gt; TempFer;
11:       TempCel = Convert(TempFer);
12:       cout &lt;&lt; &quot;\nHere's the temperature in Celsius: &quot;;
13:       cout &lt;&lt; TempCel &lt;&lt; endl;
14:               return 0;
15:    }
16:
17:    float Convert(float TempFer)
18:    {
19:       float TempCel;
20:       TempCel = ((TempFer - 32) * 5) / 9;
21:       return TempCel;
<TT>22: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: Please enter the temperature in Fahrenheit: 212

Here's the temperature in Celsius: 100

Please enter the temperature in Fahrenheit: 32

Here's the temperature in Celsius: 0

Please enter the temperature in Fahrenheit: 85

Here's the temperature in Celsius: 29.4444
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On lines 6 and 7, two <TT>float</TT>
variables are declared, one to hold the temperature in Fahrenheit and one to hold
the temperature in degrees Celsius. The user is prompted to enter a Fahrenheit temperature
on line 9, and that value is passed to the function <TT>Convert()</TT>.<BR>
Execution jumps to the first line of the function <TT>Convert()</TT> on line 19,
where a local variable, also named <TT>TempCel</TT>, is declared. Note that this
local variable is not the same as the variable <TT>TempCel</TT> on line 7. This variable
exists only within the function <TT>Convert()</TT>. The value passed as a parameter,
<TT>TempFer</TT>, is also just a local copy of the variable passed in by <TT>main()</TT>.</P>
<P>This function could have named the parameter <TT>FerTemp</TT> and the local variable
<TT>CelTemp</TT>, and the program would work equally well. You can enter these names
again and recompile the program to see this work.</P>
<P>The local function variable <TT>TempCel</TT> is assigned the value that results
from subtracting 32 from the parameter <TT>TempFer</TT>, multiplying by 5, and then
dividing by 9. This value is then returned as the return value of the function, and
on line 11 it is assigned to the variable <TT>TempCel</TT> in the <TT>main()</TT>
function. The value is printed on line 13. <BR>
The program is run three times. The first time, the value <TT>212</TT> is passed
in to ensure that the boiling point of water in degrees Fahrenheit (212) generates
the correct answer in degrees Celsius (100). The second test is the freezing point
of water. The third test is a random number chosen to generate a fractional result.</P>
<P>As an exercise, try entering the program again with other variable names as illustrated
here:</P>
<PRE><FONT COLOR="#0066FF">1:     #include &lt;iostream.h&gt;
2:
3:     float Convert(float);
4:     int main()
5:     {
6:        float TempFer;
7:        float TempCel;
8:
9:        cout &lt;&lt; &quot;Please enter the temperature in Fahrenheit: &quot;;
10:       cin &gt;&gt; TempFer;
11:       TempCel = Convert(TempFer);
12:       cout &lt;&lt; &quot;\nHere's the temperature in Celsius: &quot;;
13:       cout &lt;&lt; TempCel &lt;&lt; endl;
14:     }
15:
16:     float Convert(float Fer)
17:     {
18:        float Cel;
19:        Cel = ((Fer - 32) * 5) / 9;
20:        return Cel;
21:     }
</FONT></PRE>
<P>You should get the same results.</P>

<DL>
	<DD>
<HR>
<FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A variable has scope, which
	determines how long it is available to your program and where it can be accessed.
	Variables declared within a block are scoped to that block; they can be accessed
	only within that block and &quot;go out of existence&quot; when that block ends.
	Global variables have global scope and are available anywhere within your program.
	
<HR>

</DL>

<P>Normally scope is obvious, but there are some tricky exceptions. Currently, variables
declared within the header of a <TT>for</TT> loop <TT>(for int i = 0; i&lt;SomeValue;
i++)</TT> are scoped to the block in which the <TT>for</TT> loop is created, but
there is talk of changing this in the official C++ standard.</P>
<P>None of this matters very much if you are careful not to reuse your variable names
within any given function.
<H3 ALIGN="CENTER"><A NAME="Heading18"></A><FONT COLOR="#000077">Global Variables</FONT></H3>
<P>Variables defined outside of any function have global scope and thus are available
from any function in the program, including <TT>main()</TT>.</P>
<P>Local variables with the same name as global variables do not change the global
variables. A local variable with the same name as a global variable hides the global
variable, however. If a function has a variable with the same name as a global variable,
the name refers to the local variable--not the global--when used within the function.
Listing 5.3 illustrates these points.</P>
<P><A NAME="Heading19"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 5.3. Demonstrating
global and local variables</B></FONT><FONT SIZE="2" COLOR="#000077"><B>.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">1:   #include &lt;iostream.h&gt;
2:   void myFunction();           // prototype
3:
4:   int x = 5, y = 7;            // global variables
5:   int main()
6:   {
7:
8:        cout &lt;&lt; &quot;x from main: &quot; &lt;&lt; x &lt;&lt; &quot;\n&quot;;
9:        cout &lt;&lt; &quot;y from main: &quot; &lt;&lt; y &lt;&lt; &quot;\n\n&quot;;
10:       myFunction();
11:       cout &lt;&lt; &quot;Back from myFunction!\n\n&quot;;
12:       cout &lt;&lt; &quot;x from main: &quot; &lt;&lt; x &lt;&lt; &quot;\n&quot;;
13:       cout &lt;&lt; &quot;y from main: &quot; &lt;&lt; y &lt;&lt; &quot;\n&quot;;
14:       return 0;
15:  }
16:
17:  void myFunction()
18:  {
19:       int y = 10;
20:
21:       cout &lt;&lt; &quot;x from myFunction: &quot; &lt;&lt; x &lt;&lt; &quot;\n&quot;;
22:       cout &lt;&lt; &quot;y from myFunction: &quot; &lt;&lt; y &lt;&lt; &quot;\n\n&quot;;
<TT>23: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: x from main: 5
y from main: 7

x from myFunction: 5
y from myFunction: 10

Back from myFunction!

x from main: 5
y from main: 7
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>This simple program illustrates
a few key, and potentially confusing, points about local and global variables. On
line 1, two global variables, <TT>x</TT> and <TT>y</TT>, are declared. The global
variable <TT>x</TT> is initialized with the value <TT>5</TT>, and the global variable
<TT>y</TT> is initialized with the value <TT>7</TT>.<BR>
On lines 8 and 9 in the function <TT>main()</TT>, these values are printed to the
screen. Note that the function <TT>main()</TT> defines neither variable; because
they are global, they are already available to <TT>main()</TT>.</P>
<P>When <TT>myFunction()</TT> is called on line 10, program execution passes to line
18, and a local variable, <TT>y</TT>, is defined and initialized with the value <TT>10</TT>.
On line 21, <TT>myFunction()</TT> prints the value of the variable <TT>x</TT>, and
the global variable <TT>x</TT> is used, just as it was in <TT>main()</TT>. On line
22, however, when the variable name <TT>y</TT> is used, the local variable <TT>y</TT>
is used, hiding the global variable with the same name.</P>
<P>The function call ends, and control returns to <TT>main()</TT>, which again prints
the values in the global variables. Note that the global variable <TT>y</TT> was
totally unaffected by the value assigned to <TT>myFunction()</TT>'s local <TT>y</TT>
variable.
<H3 ALIGN="CENTER"><A NAME="Heading21"></A><FONT COLOR="#000077">Global Variables:
A Word of Caution</FONT></H3>
<P>In C++, global variables are legal, but they are almost never used. C++ grew out
of C, and in C global variables are a dangerous but necessary tool. They are necessary
because there are times when the programmer needs to make data available to many
functions and he does not want to pass that data as a parameter from function to
function.</P>
<P>Globals are dangerous because they are shared data, and one function can change
a global variable in a way that is invisible to another function. This can and does
create bugs that are very difficult to find.</P>
<P>On Day 14, &quot;Special Classes and Functions,&quot; you'll see a powerful alternative
to global variables that C++ offers, but that is unavailable in C.
<H3 ALIGN="CENTER"><A NAME="Heading22"></A><FONT COLOR="#000077">More on Local Variables</FONT></H3>
<P>Variables declared within the function are said to have &quot;local scope.&quot;
That means, as discussed, that they are visible and usable only within the function
in which they are defined. In fact, in C++ you can define variables anywhere within
the function, not just at its top. The scope of the variable is the block in which

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -