Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: declaration of ‘name’ shadows a previous local [closed]

Tags:

c++

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!

like image 828
Jon Avatar asked Jan 23 '26 09:01

Jon


1 Answers

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];
like image 146
Arnav Borborah Avatar answered Jan 25 '26 23:01

Arnav Borborah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!