Calling functions in C++<\/p>\n
#include<\/a> <iostream><\/dfn>\nusing<\/var> namespace<\/var> std;\n\nint<\/var> addition (int<\/var> a, int<\/var> b)\n{\n int<\/var> r;\n r=a+b;\n return<\/var> r;\n}\n\nint<\/var> main ()\n{\n int<\/var> z;\n z = addition (5,3);\n cout << \"The result is \"<\/kbd> << z;\n}
This program is divided in two functions: <\/span>addition<\/code> and <\/span>main<\/code>. Remember that no matter the order in which they are defined, a C++ program always starts by calling <\/span>main<\/code>. In fact, <\/span>main<\/code> is the only function called automatically, and the code in any other function is only executed if its function is called from <\/span>main<\/code> (directly or indirectly).<\/span>
In the example above, <\/span>main<\/code> begins by declaring the variable <\/span>z<\/code> of type <\/span>int<\/code>, and right after that, it performs the first function call: it calls <\/span>addition<\/code>. The call to a function follows a structure very similar to its declaration. In the example above, the call to <\/span>addition<\/code> can be compared to its definition just a few lines earlier:<\/span>
<\/span>The parameters in the function declaration have a clear correspondence to the arguments passed in the function call. The call passes two values, <\/span>5<\/code> and <\/span>3<\/code>, to the function; these correspond to the parameters <\/span>a<\/code> and <\/span>b<\/code>, declared for function<\/span>addition<\/code>.<\/span>
At the point at which the function is called from within main, the control is passed to function <\/span>addition<\/code>: here, execution of <\/span>main<\/code> is stopped, and will only resume once the <\/span>addition<\/code> function ends. At the moment of the function call, the value of both arguments (<\/span>5<\/code> and <\/span>3<\/code>) are copied to the local variables <\/span>int a<\/code> and <\/span>int b<\/code> within the function.<\/span>
Then, inside <\/span>addition<\/code>, another local variable is declared (<\/span>int r<\/code>), and by means of the expression <\/span>r=a+b<\/code>, the result of <\/span>a<\/code>plus <\/span>b<\/code> is assigned to <\/span>r<\/code>; which, for this case, where <\/span>a<\/code> is 5 and <\/span>b<\/code> is 3, means that 8 is assigned to <\/span>r<\/code>.<\/span>
<\/code><\/pre>\n<\/section>\n#TC1017<\/a> #Mastery11<\/a><\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":" Calling functions in C++\/\/ function example#include <iostream>
\nusing namespace std;<\/p>\n
int addition (int a, int b)
\n{
\n int r;
\n r=a+b;
\n return r;
\n}<\/p>\n
int main ()
\n{
\n int z;
\n z = addition (5,3);
\n cout << “The result is ” << z;… Continue reading