[Solved] How can I save a variable in my function to use it again?


Onk_r has the right answer: static variables within the body ({}) of a function ‘stick around’. Specifically, the expression which initializes the value of a static variable within a function body is executed only once, so the next time you call that function whatever value it had last will remain.

However, that won’t solve your problem: your code is written with the assumption that every time you use a variable the expression that initialized it will be executed. When you use the name damage, for instance, the program will not execute the function blade(). Damage will only receive the value returned by blade() the one time, when you declared the variable damage:

int damage = blade();

That line only ever executes once in the whole lifetime of the program. Similarly, newHP will only ever have the value of health - damage at the time it was initialized. When damage was initialized, if blade() returned 8, then newHP will always have the value 42;

C++ doesn’t store expressions; it evaluates them. That is what the type system ensures: the type stored in damage is int, it cannot have the type “expression” (not a thing in C++, though there are all kinds of ways implementing something like that). When you assign a variable, the value of the expression is stored, not how it was calculated. Every time the user attacks you really need to do something like:

newHP = health - blade();
/* Output message */
health = newHP;

Like Norhther said.

You are relying on functions to store state here, too, which isn’t bad but in C++ you can, and generally should, do better. Specifically, class Hollow or the easier struct Hollow would be better than some variables floating around inside main().

2

solved How can I save a variable in my function to use it again?