c++functionglobal-variables

Declaring Global variable inside of a function in C++


I have a function inside a class. I want to declare about 10 global variables of different types: vector, queue, int, 2d-vector etc., How do I do this?

Also I just cant declare the variables outside of the function, I want the variables to be declared inside the function.


Solution

  • Global variables can't be defined inside a function in C++. They can technically be declared inside a function in a non-definition, but I highly doubt that this is what you want. It is a feature that exists for historical reasons and is not really used in practice.

    C++ has lexical scoping, so constructs like global in Python, which has dynamic scoping, that allows introducing a global variable inside a function, can't work in C++.

    Whatever you are trying to do is probably not dependent on being able to do this though. Unfortunately you didn't provide sufficient context to give a solution.

    Also, as a general guideline, always try to avoid global variables in C++, except when they are constants that can be marked constexpr.