0

I was trying to make a program takes a filePath as std::string which is dependent upon basePath(path of my project) and a relative const path.

if I modify basePath then it doesnt reflect any change to filePath.

#include <iostream>
using namespace std;

string basePath =  "C:\\Pime\\"; 
// main location of my project

string filePath = basePath + "folder\\";
// relative location in my project

int main() {
    basePath = "D:\\Pime\\ ";
    std::cout << filePath<< std::endl;

    // prints-> C:\Prime\folder
    return 0;
}

How to avoid this. Is Solution related to volatile keyword.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • 1
    `dependent variable` No such thing in C++ as a "*dependent*" variable. `filePath` is a regular string variable, initialized to `"C:\\Pime\\folder\\"` and never modified after that. – dxiv Sep 12 '20 at 02:51
  • 2
    you should get a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn from there. Variables don't work how you expect them to work. – bolov Sep 12 '20 at 02:54
  • yeah, But how to avoid this behaviour without changing much of its implementation –  Sep 12 '20 at 02:55
  • @vectorX You can't. You need to recompute the value every time it changes. Simple as that. Correct me, If I am wrong, but my guess is that you come from a background such as "Angular" or "Excel". These are programmed in such a way to monitor changes and recompute dependent variables automagically. All programming languages (that I am aware of) do not do that. – Julian Kirsch Sep 12 '20 at 03:23
  • I love when we show the OP is misunderstanding some fundamental concept and he/she is only interested in the "whatever, just give me the codes" – bolov Sep 12 '20 at 03:37

2 Answers2

0

There are no such things like "dependent variables" in C++.

filePath need to be computed every time you get its value. The simplest solution is to make it a function:

std::string basePath =  "C:\\Pime\\"; 

std::string getFilePath() { return basePath + "folder\\"; }
bolov
  • 72,283
  • 15
  • 145
  • 224
0

You're confusing C++ variables for the recursively expanded variables from makefiles.

foo="hello"
bar="$foo!"
foo+=" world" #$bar is now "hello world!"

C++ doesn't have this. The value of a variable is determined at assignment time, like simply expanded variables.

See https://www.gnu.org/software/make/manual/html_node/Flavors.html for the difference.

Filipp
  • 1,843
  • 12
  • 26
  • you can't know know with what the OP is confusing variables. Maybe it's the makefile, maybe it's excel, maybe it's the concept of math variable. – bolov Sep 12 '20 at 03:35