Pretty straightforward, I'm relearning C++ and I'm up to pointers. I understand the basic concept, but I'm having a little trouble. What would the syntax for calling this function be?
void getTime(int& hours, int& minutes, int& seconds) const
{
hours = hr;
minutes = min;
seconds = sec;
}
The point of the function, as you've probably guessed, is to return the time in hours, minutes and seconds to three pointers in located in whatever scope the function call is in. Assume that hr, min, and sec have already been defined.
Also, if anyone would like to elaborate on the pointers a little (particularly when to use & and when to use *) that would be greatly appreciated. Thank in advance.
Your function signature uses &, which denotes a pass-by-reference. This means that you simply invoke your function as
int h, m, s;
// ... code ...
getTime(h, m, s);
Because your function passes these arguments by reference, whenever getTime() changes one of the arguments passed, the changes propagate to outside the function, as opposed to arguments passed by value where changes are limited to the function scope.
You can achieve a similar effect by passing pointers to variables instead:
void getTime(int * hours, int * minutes, int * seconds)
{
// do stuff
}
// ... code ...
int h, m, s;
getTime(&h, &m, &s);
In the latter context, the & is the address-of operator. By dereferencing the addresses passed, your function can make changes to memory outside its function scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With