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

📄 ch05.htm

📁 一本好的VC学习书,本人就是使用这本书开始学习的vc,希望能对大家有帮助
💻 HTM
📖 第 1 页 / 共 5 页
字号:
header is exactly like the function prototype, except that the parameters must benamed, and there is no terminating semicolon.</P><P>The body of the function is a set of statements enclosed in braces. Figure 5.3shows 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">Figure5.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 isnot required to list their names, only their types. A prototype always ends witha semicolon (;). A function definition must agree in return type and parameter listwith its prototype. It must provide names for all the parameters, and the body ofthe function definition must be surrounded by braces. All statements within the bodyof the function must be terminated with semicolons, but the function itself is notended 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> statementscan legally appear anywhere in the body of the function. Every function has a returntype. 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 returna 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 parametersvoid PrintMessage(int messageNumber); // returns void, has one parameterint 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 theopening 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 ProgramFlow&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 variableswithin the body of the function. This is done using local variables, so named becausethey exist only locally within the function itself. When the function returns, thelocal variables are no longer available.</P><P>Local variables are defined like any other variables. The parameters passed into the function are also considered local variables and can be used exactly as ifthey had been defined within the body of the function. Listing 5.2 is an exampleof 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 useof 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: 212Here's the temperature in Celsius: 100Please enter the temperature in Fahrenheit: 32Here's the temperature in Celsius: 0Please enter the temperature in Fahrenheit: 85Here'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 holdthe temperature in degrees Celsius. The user is prompted to enter a Fahrenheit temperatureon 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 thislocal variable is not the same as the variable <TT>TempCel</TT> on line 7. This variableexists 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 namesagain and recompile the program to see this work.</P><P>The local function variable <TT>TempCel</TT> is assigned the value that resultsfrom subtracting 32 from the parameter <TT>TempFer</TT>, multiplying by 5, and thendividing by 9. This value is then returned as the return value of the function, andon 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 passedin to ensure that the boiling point of water in degrees Fahrenheit (212) generatesthe correct answer in degrees Celsius (100). The second test is the freezing pointof 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 illustratedhere:</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, variablesdeclared 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, butthere 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 nameswithin 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 availablefrom any function in the program, including <TT>main()</TT>.</P><P>Local variables with the same name as global variables do not change the globalvariables. A local variable with the same name as a global variable hides the globalvariable, 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. Demonstratingglobal 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();           // prototype3:4:   int x = 5, y = 7;            // global variables5:   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: 5y from main: 7x from myFunction: 5y from myFunction: 10Back from myFunction!x from main: 5y from main: 7</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>This simple program illustratesa few key, and potentially confusing, points about local and global variables. Online 1, two global variables, <TT>x</TT> and <TT>y</TT>, are declared. The globalvariable <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 thescreen. Note that the function <TT>main()</TT> defines neither variable; becausethey 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 line18, 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>, andthe global variable <TT>x</TT> is used, just as it was in <TT>main()</TT>. On line22, 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 printsthe values in the global variables. Note that the global variable <TT>y</TT> wastotally 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 outof C, and in C global variables are a dangerous but necessary tool. They are necessarybecause there are times when the programmer needs to make data available to manyfunctions and he does not want to pass that data as a parameter from function tofunction.</P><P>Globals are dangerous because they are shared data, and one function can changea global variable in a way that is invisible to another function. This can and doescreate bugs that are very difficult to find.</P><P>On Day 14, &quot;Special Classes and Functions,&quot; you'll see a powerful alternativeto 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 functionin which they are defined. In fact, in C++ you can define variables anywhere withinthe function, not just at its top. The scope of the variable is the block in whichit is defined. Thus, if you define a variable inside a set of braces within the function,that variable is available only within that block. Listing 5.4 illustrates this idea.</P><P><A NAME="Heading23"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 5.4. Variablesscoped within a block.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:    // Listing 5.4 - demonstrates variables2:    // scoped within a block

⌨️ 快捷键说明

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