Using variables outside the function it was declared in?

Basically I have this variable declared in a function that I want to work with in my "main" function. How do I do this the best way possible?
Last edited on
That question needs some background context, otherwise there may be many answers.

But one suggestion is to define the variable in main() and pass it by reference to the other function. Depending on what it is you are trying to achieve, that may or may not be appropriate.
Dynamic allocation or return by value. Former returns a pointer to allocated memory (and you have to handle deallocation appropriately. Latter .. you essentially declare a variable in the main for the return value.

Third option: declare in main and pass to function by reference or by pointer.
Lets say I have a function with a while loop that adds 1 to x as long as x is less than 5. Now that x has the value of 5 I want to be able to use x in my main function. X is declared in my function but I want to use it in an if statement in main.
I want to use it in an if statement in main

Just put return x; in the function if it is just the value (the number 5) that you need.
Topic archived. No new replies allowed.