Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pass by address and reference

Status
Not open for further replies.

Grizant

Programmer
Oct 6, 2002
7
US
How would I write a function that receives a floating point number and the addresses of the integer variables named quaters, dimes, nickles, and pennies; the function should determine the number of quarters, dimes, nickles, and pennies in the number passed to it and write these values directly into the respective variables declared in its calling function.
 
Hi,
The function declaration would be
void Money(double nDollarValue, int& nQuarters, int& Dimes, int& Nickels, int& Pennies);

The function definition would be written as
// Simple straightforward solution
void Money(double nDollarValue, int& nQuarters, int& nDimes, int& nNickels, int& nPennies)
{
int work = (int) ((nDollarValue + .005) * 100.0);
nQuarters = (int) (work / QUARTER);
work = work % QUARTER;
nDimes = (int) (work / DIME);
work = work % DIME;
nNickels = (int) (work / NICKEL);
work = work % NICKEL;
nPennies = (int) (work / PENNY);
}

and the main body of the program would look like:
enum {QUARTER = 25, DIME = 10, NICKEL = 5, PENNY = 1};

int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
float nDollarValue = 3.17f;
int nQuarters, nDimes, nNickels, nPennies;
Money(nDollarValue, nQuarters, nDimes, nNickels, nPennies);
return 0;
}

Hope this helps [atom]


 
Ok, It did help, but isnt that passing a reference and not the addresses of the integervariables.
 
Hi,
When you pass by reference, the compiler generated code is
really passing the address of the variable, and automatically dereferencing the pointers for you. However,
if you want an example of explicitly passing addresses, just change the function declaration in my example to

void Money(double nDollarValue, int* nQuarters, int* Dimes, int* Nickels, int* Pennies);

And change the function definition to:

void Money(double nDollarValue, int* nQuarters, int* nDimes, int* nNickels, int* nPennies)
{
int work = (int) ((nDollarValue + .005) * 100.0);
*nQuarters = (int) (work / QUARTER);
work = work % QUARTER;
*nDimes = (int) (work / DIME);
work = work % DIME;
*nNickels = (int) (work / NICKEL);
work = work % NICKEL;
*nPennies = (int) (work / PENNY);
}

The function call would then be:

Money(nDollarValue, &nQuarters, &nDimes, &nNickels, &nPennies);

The results will be the same.

This should help more [bigsmile]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top