+ 2
Local to Global Variabel in C++ ?
How to declare a local variable in the scope but we can access it from outside the scope, in the sense that we set the local state of the variable to be a global variable
7 Answers
+ 5
You can get your local variable depending on their storage specifier. Most static variables are not destroyed out of their scope and using the reference operator, i think this is possible
https://code.sololearn.com/cYZKCN6VzdG9/?ref=app
+ 3
Use dynamic memory allocation
+ 2
It's not possible, because variables are destroyed outside the scope.
The only way is to create a global variable:
int a = 1;
void f()
{
a = 100;
}
+ 2
Luk Mm okay, i think there is a rule or sign that make it happen
+ 2
You can use static variables as Mirielle[ Exams ] demonstrated.
But l want to warn you that using global variables is considered bad practise. Everything can get confusing really fast, especially when using it as Mirielle[ Exams ] showed. I don't know if that comes into the category of badly written code, but I would try to avoid it as much as possible. See this:
https://www.learncpp.com/cpp-tutorial/why-global-variables-are-evil/
+ 2
Mirielle[ Exams ]
XXX
Useful info, but i'll study that thx
+ 1
1. Global variables which arent constant are considered a bad practise because they can easily be changed somewhere else in the code, (implicitly or explicitly).
2. However, there's nothing as "badly written code" in the solution i provided cos the author should be responsible for the control of 1 above.