Skip to content
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

Error for variable only set but never read #12047

Open
wooster0 opened this issue Jul 8, 2022 · 0 comments
Open

Error for variable only set but never read #12047

wooster0 opened this issue Jul 8, 2022 · 0 comments
Labels
proposal This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone

Comments

@wooster0
Copy link
Contributor

wooster0 commented Jul 8, 2022

Main idea

pub fn main() void {
    var x = 1;
    x = 5; // Now Zig thinks `x` was "used",
           // but it was only ever written to, never read
}

This compiles without an error.
But GCC has this feature that Zig doesn't have:

int main() {
    int x = 1;
    x = 5;
}
$ gcc x.c -Wunused-but-set-variable
x.c: In function ‘main’:
x.c:2:9: warning: variable ‘x’ set but not used [-Wunused-but-set-variable]
    2 |     int x = 1;
      |         ^

Recently when messing around with C I found this warning really nice. Now I want it in Zig too. I think it's really useful and can prevent many logic errors.

So I propose having this feature in Zig too and making it an error if you only ever set a variable and never actually read it.

Extra

In fact, we might make it so smart that even this will trigger an error because the second write is useless and you aren't reading from x before the second write:

pub fn main() void {
    var x: u8 = 1;
    x = 5;
    _ = x;
}

This is more advanced but might lead to some other undesirable things (haven't thought this extra through too much) so this is optional.
So basically you'd be required to read a variable at least once before you can write it again.
This is something that GCC doesn't have.

See also: #335
See also: nektro/ziglint#15
See also: #2304

@Vexu Vexu added the proposal This issue suggests modifications. If it also has the "accepted" label then it is planned. label Jul 8, 2022
@Vexu Vexu added this to the 0.11.0 milestone Jul 8, 2022
@andrewrk andrewrk modified the milestones: 0.11.0, 0.12.0 Apr 9, 2023
@andrewrk andrewrk modified the milestones: 0.13.0, 0.12.0 Jul 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
proposal This issue suggests modifications. If it also has the "accepted" label then it is planned.
Projects
None yet
Development

No branches or pull requests

3 participants