Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring vector as global variable in C++

Tags:

People also ask

Can we declare vector globally?

Is it a good practice to declare a vector as global in C++? No. Avoid global variables, irrespective of their types.

Is it safe to use global variables in C?

You should typically not use global variables unless absolutely necessary because global variables are only cleaned up when explicitly told to do so or your program ends. If you are running a multi-threaded application, multiple functions can write to the variable at the same time.

How do you declare a global variable in C++?

You can declare global—that is, nonlocal—variables by declaring them outside of any function definition. It's usually best to put all global declarations near the beginning of the program, before the first function. A variable is recognized only from the point it is declared, to the end of the file.


Is it a good practice to declare a vector as global in C++?

This is what I did.

#include <vector>
std::vector<int> vec;

My program compiles successfully, but I am not sure whether this could lead to a runtime error under certain circumstances. According to my understanding, the memory for a global variable will be allocated at compile time, and the compiler may reserve a limited amount of memory to which this vector can expand. Upon hitting this limit, what is being written can eat into the memory used by another variable.

Please advise.