Skip to content

switch silently ignores invalid enum values when using else branch #9753

@mjoerussell

Description

@mjoerussell

Zig version: 0.9.0-dev.477+00e944f71

Noticed this while working on zdb. I'm not sure if this is technically a bug, but it seems inappropriate to not show this error here. Here's a minimal repro of the situation that could cause this:

// test.h
void setBadEnumVal(unsigned int *value) {
  *value = 5;
}
// main.zig
const c = @cImport({
  @cInclude("test.h");
});

const Test = enum(c_uint) {
  a = 0,
  b = 1,
  c = 2,
};

pub fn main() {
  var val: Test = undefined;
  
  c.setBadEnumValue(@ptrCast([*c]c_uint, &val));

  switch (val) {
    .a, .b => {},
    else => {}
  }
}

If you include every switch case, then the error you get is reached unreachable code. But if you use an else branch, then
the code goes into that branch without complaint. However, if val is ever referenced then the code will panic with invalid enum value.

I can see how this makes sense in one view, since if val is never directly referenced, why does it matter if the enum value is invalid? However this seems wrong to me, since my assumption looking at this could would be that val is being referenced, inside the switch statement. It seems potentially dangerous to allow invalid enum values to go right to an else block instead of panicking with invalid enum value like any other reference would.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSolving this issue will likely involve adding new logic or components to the codebase.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions