English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have this function name
void playOneGameOfCraps(bool& win, int& numRolls);
1.)How do I write this as a function call? It says I am shadowing a parameter.
2.)In my function if I "win" the game of craps it is
suppose to return true but how do I return it if it is a void function? ...and where do you return it to?
Same with lose = false, and number of rolls in that game. How does this work when there are only 2 parameters?
I am confused on how this works. Thanks for any help.

2007-03-09 08:03:39 · 4 answers · asked by jnjn 2 in Computers & Internet Programming & Design

4 answers

Whenever you need more than one returned value from a function, you make that function a void function and you pass to it the things you want returned by reference. (Passing by reference requires that you add the and sign '&' to the type of the variable just like you did with your "playOneGameOfCraps" function.

Q: Now, how can you return those two values from the function?

A: Actually you are not really "returning" anything from the function, you are just assigning values to the parameters of the function. Here is an example:

int main( )
{
int number1 = 10;
int number2 = 20;

function(number1 , number2);

// The following line will print 5 & 6 (not 10 & 20) because you
// changed the values of number1 and number2 in the
// function below. If the function below did not have the &'s
// in front of the parameter types, the following line would print
// 10 & 20.
cout << number1 << endl << number2;

return 0;
}

void function(int& a, int& b)
{
a = 5;
b = 6;
}

I hope this helps!!

2007-03-09 10:58:43 · answer #1 · answered by Silver_Sword 3 · 0 1

The function is designed that way because it needs to return two parameters, whether or not you won and how many rolls it took. To achieve this, it passes them by reference, so:

bool isWinnter;
int numRolls;
playOneGameOfCraps(isWinner, numRolls);

When playOneGameOfCraps returns, the value of isWinner and numRolls will reflect your win status, and the number of rolls it took.

2007-03-09 08:14:32 · answer #2 · answered by Pfo 7 · 0 0

it works like this:

BOOL Win;
int Rolls;

//pass the address of the parameters to playonecameofcraps
playOneGameOfCraps(&Win, &Rolls);
if (Win)
//you win
else
//you lose
//Rolls contains the number of rolls it took


void playOneGameOfCraps(bool& win, int& numRolls);
{
//your code here
*numRolls = blah; //blah is number of rolls
if (youwin)
*win = 1;//if you win
else
*win = 0;//you lose
}

2007-03-10 01:19:04 · answer #3 · answered by justme 7 · 0 1

the values will be returned to win and numRolls because they are passed as references!

2007-03-09 08:10:04 · answer #4 · answered by agent-X 6 · 2 1

fedest.com, questions and answers