I have this very simple snippet here:
std::string testName;
if (argc < 2) {
std::string testName = "default";
}
else {
std::string testName = argv[2];
}
For some reason the compiler gives me 2 warnings;
warning: declaration of ‘testName’ shadows a previous local [-Wshadow]
std::string testName = "default";
^
note: shadowed declaration is here
std::string testName;
^
warning: declaration of ‘testName’ shadows a previous local [-Wshadow]
std::string testName = argv[2];
^
note: shadowed declaration is here
std::string testName;
^
I am feeling rusty and stupid, appreciate the help!
The warning you are getting is due to the fact that you are declaring a new variable inside your conditionals. To fix, remove the std::string inside the conditionals:
std::string testName;
if (argc < 2) {
testName = "default"; // Prefixing with std::string creates a new variable
}
else {
testName = argv[2]; // Not doing so assigns the old variable
}
If you wanted to do this all on one line, you could do the following with the ternary operator, since initialization could be considered better than declaring and assigning later.
std::string testName = argc < 2 ? "default" : argv[2];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With