auto scope question?

Steven Schveighoffer schveiguy at gmail.com
Wed Oct 26 01:13:05 UTC 2022


On 10/25/22 6:07 PM, WhatMeWorry wrote:
> I'm naturally getting a undefined identifier `s` error in the return.  
> Is there some way to refactor my code?  I tried to declare s outside of 
> the else brackets like:
> 
> auto screen = executeShell(cmdLine);
> auto s;
> ...
> {
>      s = screen.output.findSplit("REG_SZ");
> }
> 
> but that doesn't compile either.
> 
> 
> 
> string[] getPath(string cmdLine)
> {
>      auto screen = executeShell(cmdLine);
> 
>      if (screen.status != 0)
>      {
>          writeln(cmdLine, " failed");
>      }
>      else
>      {
>          writeln("screen.output = ", screen.output);
>      auto s = screen.output.findSplit("REG_SZ");
>          writeln("s[0] = ", s[0]);
>          writeln("s[1] = ", s[1]);
>          writeln("s[2] = ", s[2]);
>      }
>      return (s.split(';'));  // Error: undefined identifier `s`
> }

As Ali mentioned, your logic is faulty -- you seem to write that the 
command failed, but then return something anyway.

Also, you are returning `string[]`, so just declaring `string[] s;` 
should be enough.

However, I did want to mention that if you do want to hoist a difficult 
to name type outside where it is declared with an auto, you can use 
`typeof`:

```d
typeof(screen.output.findSplit("")) s;
```

In this case, it's just `string[]`, but the idea here is you can name a 
type without naming it, by using `typeof` on the expression you would 
have called.

Hope this helps further your D knowledge ;)

-Steve


More information about the Digitalmars-d-learn mailing list