+ 3
Global variables in C++
Can I create a global variable inside main() or other function?
10 Antworten
+ 3
Максим Казадаев, here I wrote a simple program to show how to declare a global variable and use it to handle a uni-dimensional array, which size is unknown at compile-time but is user-defined at run-time. Which means its length is dynamical. In this program, we use the power of dynamic memory allocation. The source code can have multiple variations. You may play around with it and try to use even a more complex logic. 😉
On PC, in Visual Studio, for example, the output is easier to see than here in Code Playground.
https://code.sololearn.com/cqXZIM1V6oMg/?ref=app
+ 7
Yes you can , but that will no longer be a global variable. It will be known as local variable and will be destroyed as soon as it goes out of scope.
+ 5
Максим Казадаев that is the problem with arrays, its size should be known before hand.
you can use dynamic memory alocation to create an array of required size at runtime. But this might lead to memory leak.
But there is a safe alternative to this in C++ ,which is famously known as *vector*
+ 4
A variable which can be accessed by all the available functions is known as global variable . If u declare a variable inside the main() than its scope will be inside main() only u can't access it in other functions so that will be local only . Global variable should be declared outside of all the function than only it will be known as global.
To use a variable as global which is declared inside main () we can use the concept of pointer . We can use the variable of main() by its reference.
+ 2
I need to declare an array of size that user will input and to use this array in functions without passing it into arguments. How can I create this dinamic array (I don't know the size before main() function)?
+ 2
You can create a global array by declaring array before void main() or int main()
Like this
//Header files
int arr[5];
//Main
This array can be used by any method/functions without passing as arguement which is what you want to do. And as you said size is not defined i.e dynamic array, you can use new operator to declare an array of size given by user.
+ 2
In case, if sololearn doesn't have lesson for new operator, here is the link you can refer.
https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-memory/
Happy coding😊
+ 1
Thank you for your support! I am realy inspired by these examples.
+ 1
No, if you create any variable inside method then it is no longer global that will be local variable, which can be accessed only inside the methods.
Global variable should be outside the method and inside the class.