Function pointers; imagine that you didn't know at the time of compiling which function would be used. You could have the function pointer, and during running of the program, the decision would be made. For example, we could have two functions with prototypes like this:
1 2
|
float sin(float input);
float cos(float input);
|
And a function pointer; that is, a pointer that we specify is pointing to a function that takes a float, and returns a float. The value of that pointer could flip between the two functions repeatedly during running, as needed, and when we use it, we effectively say to the compiler "use the function that this pointer points to at the time of running - you don't need to know or care what the function does, just that it takes a float and returns a float". This is a trivial example, and there are other ways to do this (especially with C++), but it's a powerful low-level mechanism.
I'm not sure I could think of a good reason at this point to know the location of something in memory |
Didn't you just do exactly that in your code above when you passed, into your function, a pointer that is the location of EnemyHp in memory? :) That said, the better C++ way is to use a
reference, like this:
Be warned - this shows another,
completely separate use of the "&" symbol.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <iostream>
#include <string>
using namespace std;
void DealDamage(int& EnemyHp, int damage, string EnemyName);
int main()
{
int EnemyHp = 100;
int Damage = 12;
cout << "EnemyHp before function call: " << EnemyHp << endl;
DealDamage(EnemyHp, Damage, "a rat");
cout << "EnemyHp after function call: " << EnemyHp << endl;
return 0;
}
void DealDamage(int& EnemyHp, int damage, string EnemyName)
{
EnemyHp-=damage;
cout << "sword does " << damage << " damage " << "to " << EnemyName << endl;
}
|
The difference is essentially here:
1 2
|
void DealDamage(int& EnemyHp, int damage, string EnemyName);
void DealDamage(int EnemyHp, int damage, string EnemyName);
|
As you found out in much earlier threads, in the second function, you pass in the values, and whatever happens to those values is lost when the function ends. This is because each value passed in is actually a
copy of the original, and that copy is destroyed when the function ends. This is known as pass-by-value.
In the first prototype there, that "&" symbol changes the meaning. It means "the first parameter is a reference to an int". The difference is that a copy is not made; the function will work directly with the original value - the exact same bit of memory, not a copy of the value made just for the function. Clearly, then, if it's working with the original object, any changes happen to that original object, and those changes are permanent - when the function ends, the original has been changed.