With my code below I'd like to not have to use "string name" as a global variable if I don't have to. I'd like to declare it in the getName() function but be able to call it in the guessNumber() function on where I have the welcome message. With my code, how would I go about that?
I don't see how you could use it in getName() and use it in guessNumber().
But what you could do is declare it in your main and pass it between your functions with references.
@deathslice That code seems to compile fine and makes the example more clear, however when it's supposed to print out the Welcome << name <<..... it leaves name blank so the output is:
"Welcome , Let's get started" even when entering a name.
EDIT: Yes I replaced your "x" variable name with my original variable name "name" before testing.
The problem with deathslice's code is that at line 11, x is passed by value. getName() updates x, but x is never returned to the caller. You have two choices.
1) pass x by reference instead of by value.
2) Declare getName as returning a string, then return x.
For this type of thing would it be better to continue to just use std::string name as a global variable?
I am trying to use good practice with my code even with the smallest of projects and figured using as few global variables as possible would be best, though I could be wrong here. Am I making more work than I should, or am I right in that I shouldn't use "name" as a global variable?
Now I need to figure out what exactly is going on here so I can actually learn something. My original code made sense when name was a global var, now it's a tad confusing.