Hi
Today the instructor was trying to teach us how the following code works. To be truthful I couldn't understand anything.
First thing he changed in the today's program was that he made declared the user defined function within the int main though in the past he told us to declare it before entering int main. Please have a look on CODE 2 which you would understand what I'm saying. I don't understand the reason for this.
1: I copied the following CODE 1 onto my flash drive. You can see that the declaration for the user defined function has been made inside the int main. What's the reason for this change?
2: What kind of data type is this "int&"?
3: Could you please tell me in simple words what that passing of arguments by reference means? What's the advantage of this practice.
Please keep your replies as simple as possible. Thank you very much.
CODE 1:
Code:
// orders two arguments passed by reference
#include <iostream>
using namespace std;
int main()
{
void order(int&, int&); //prototype
int n1=99, n2=11; //this pair not ordered
int n3=22, n4=88; //this pair ordered
order(n1, n2); //order each pair of numbers
order(n3, n4);
cout << "n1=" << n1 << endl; //print out all numbers
cout << "n2=" << n2 << endl;
cout << "n3=" << n3 << endl;
cout << "n4=" << n4 << endl;
return 0;
}
//--------------------------------------------------------------
void order(int& numb1, int& numb2) //orders two numbers
{
if(numb1 > numb2) //if 1st larger than 2nd,
{
int temp = numb1; //swap them
numb1 = numb2;
numb2 = temp;
}
}
CODE 2:
Code:
// calculating area of a circle using user-defined function
#include <iostream>
#include <cstdlib>
using namespace std;
float area(float dummy);
int main()
{
float r; float a;
cout << "enter radius: "; cin >> r;
a = area(r);
cout << a;
system("pause");
return 0;
}
//------------------------------------
// area(int), function definition
float area(float dummy)
{
float Area;
Area = 3.1416*(dummy*dummy);
return Area;
}
//--------------------------------------