-1

I've looked at other topics, the answers usually solve the problem using parameters, but this is not the way I want. I'm new to C++, I was developing NodeJS before. Can we make a variable that we can access from the region we want like in NodeJS?

string read_from_ram(string& key) {
   //how can I access and edit keysDB and valuesDB variables from here
}

int main(int argc, char* argv[]) {
    auto [keysDB, valuesDB] = read_from_disk();
}
GreXLin85
  • 97
  • 1
  • 10

3 Answers3

1

You have to pass those variables to your function. That's something every textbook would have told you in the very first chapters.

Guessing the types, this could be what you want:

std::string read_from_ram(const std::string& key,
        const std::vector<std::string>& keys,
        const std::vector<std::string>& values)
{
   // access keys and values here
}

int main(int argc, char* argv[])
{
    auto [keysDB, valuesDB] = read_from_disk();
    auto foo = read_from_ram("foo", keysDB, valuesDB);
}

You could also make them global, but that would probably be a bad design choice.

Stefan Riedel
  • 796
  • 4
  • 15
1

No. You'll have to pass a pointer/reference to the function with the way you currently have it written, or set it as a global variable (which is typically frowned upon unless required by the problem scope).

Another potential idea would be to make an object.

class MyClass { 
  private:
    string key;
  public:            
    string read_from_ram(string& key) {};
};

In this case, key would be accessible from anywhere inside your class.

blackbrandt
  • 2,010
  • 1
  • 15
  • 32
1

If I understand you correctly, then you want to access a variable globally. If that is the case than you just have to define a global variable, which means define a variable outside of all functions, usually this is done under your includes. Warning: Usually you should avoid global variables because they can be manipulated from anywhere in the program and generic names can also be dangerous.

bluejambo
  • 221
  • 1
  • 11