Unable to access a variable declared inside an if statement (Error: is shadowing variable)

Simen Kjærås simen.kjaras at gmail.com
Wed May 27 11:13:09 UTC 2020


On Wednesday, 27 May 2020 at 11:03:51 UTC, BoQsc wrote:
> I'm lacking knowledge on how to achieve what I want and getting 
> an error.
> What is the correct way to do what I tried to achieve in this 
> code?
> Everything was intuitive until I started to add notice variable 
> to the writeln. Rdmd says  variable `notice` is shadowing 
> variable.
>
>> 		if (driveLetter.exists){
>> 			auto directory = "/Backup";
>> 			if ((driveLetter ~ directory).exists){
>> 				auto notice = "Backup directory exists.";
>> 				
>> 			}
>> 			writeln(driveLetter, notice);
>> 		}

Variables only live in a specified scope, starting from where 
they are declared, and ending when they reach the '}' indicating 
the end of said scope.

In you case, 'notice' only lives inside the if ((driveLetter ~ 
directory).exists) scope, and doesn't exist outside. In order to 
fix this, you will need to declare it outside:

     if (driveLetter.exists) {
         auto directory = "/Backup";
         auto notice = "Backup directory does not exist.";
         if ((driveLetter ~ directory).exists) {
             notice = "Backup directory exists.";
         }
         writeln(driveLetter, notice);
     }

This also makes it clearer what value 'notice' will have when the 
backup directory doesn't exist - in your case you haven't 
assigned it any value in that case.

--
   Simen


More information about the Digitalmars-d-learn mailing list