vendredi 27 février 2015

Referencing a variable in a function c++

I'm trying to make sure that I understand what the use of the ampersand to reference a variable is. I know other similar questions have been asked but I would like to see if the code example I give uses it correctly.


example code:



// function prototype
GetBalance(float &balance);

int main()
{
float balance;
bool choice = true;

if (choice == true)
GetBalance(float &balance);
else
cout << "error" << endl;

return 0;
}

GetBalance(float &Balance)
{
cout << "please enter the balance: " << endl;
cin >> balance;

}


So in the main function the float variable is declared.


The function GetBalance references the variable declared in the main function. So that when the user enters a balance, the input is assigned to the balance variable.


Is this correct?


If not is what I want to do possible?


I would like to assign / pass the amount entered during the GetBalance functionto the variable "balance" declared in main().


Aucun commentaire:

Enregistrer un commentaire