+ 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

28th Mar 2021, 10:25 AM
Unknown Ambusher 🗡️
Unknown Ambusher 🗡️ - avatar
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
28th Mar 2021, 11:07 AM
Mirielle
Mirielle - avatar
+ 3
Use dynamic memory allocation
29th Mar 2021, 7:17 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
+ 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; }
28th Mar 2021, 10:49 AM
Luk
Luk - avatar
+ 2
Luk Mm okay, i think there is a rule or sign that make it happen
28th Mar 2021, 11:03 AM
Unknown Ambusher 🗡️
Unknown Ambusher 🗡️ - avatar
+ 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/
28th Mar 2021, 11:32 AM
XXX
XXX - avatar
+ 2
Mirielle[ Exams ] XXX Useful info, but i'll study that thx
28th Mar 2021, 12:03 PM
Unknown Ambusher 🗡️
Unknown Ambusher 🗡️ - avatar
+ 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.
28th Mar 2021, 11:37 AM
Mirielle
Mirielle - avatar