Skip to content

Add a new section that explains the variable scope problem with for-loop #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/coming-from-hlsl.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,36 @@ int MyFunc()
}
```

#### Variable scope in `for`-loop follows the old FXC rule
The older version of HLSL compiler, FXC, had a little different variable scope for the `for`-loop compared to other languages.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By default, the language is slang so you will never run into this issue. This is only the case if the user explicitly specified -lang hlsl. We should simply advise users to not set input language to HLSL.


FXC produces an error or a warning for the following code:
```
for (int i = 0; i < 4; i++) {...}
for (int i = 0; i < 4; i++) {...} // FXC prints an error or warning
```

The warning looks like the following:
```
my_shader.hlsl(8,14): warning X3078: 'i': loop control variable conflicts with a previous declaration in the outer scope; most recent declaration will be used
```

This is no longer the case with the recent HLSL compiler, DXC. But Slang respects the old FXC rule and you may encounter an error like:
```
error 30200: declaration of 'i' conflicts with existing declaration
```

To resolve the problem, you can modify the shader to reuse the previously declared variable:
```
for (int i = 0; i < 4; i++) {...}
for (i = 0; i < 4; i++) {...} // Reuse the variable declared from the previous for-loop
```

Or, you can explicitly set the language to be `slang`:
```
slangc.exe -lang slang -stage vertex -entry vertexMain my_shader.hlsl
```


#### Member functions are immutable by default
By default, Slang member functions do not allow mutations to `this`. It is as if the member function has the `const` keyword in C/C++.
Expand Down
Loading