Skip to content

[Clang] Incorrect "Case value is not a constant expression" #142566

@kezyr

Description

@kezyr

Problem:
Clang (both clang++ and Clangd) incorrectly produces an error "Case value is not a constant expression" when attempting to use a static enumerator (e.g., State::EnumType::A) accessed through an instance of its containing struct (state.A) within a switch statement's case label. This should be a valid constant expression according to the C++ standard.

Expected Behavior:
The code should compile successfully, as state.A refers to the constant enumerator State::EnumType::A and is suitable for a case label. GCC compiles this code without issues.

Reproducer Code:

struct State {
    enum EnumType { A, B };

    EnumType value;

    constexpr operator EnumType() const noexcept { return value; }
};

struct Foo {
    State state;

    void workaround() {
        auto stateCopy = state;

        switch (stateCopy) {
            case stateCopy.A: // This compiles successfully with Clang.
            case stateCopy.B:
                break;
        }
    }

    void shouldCompile() {
        switch (state) {
            case state.A: // Clang error: "Case value is not a constant expression clang(expr_not_cce)"
            case state.B:
                break;
        }
    }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:frontendLanguage frontend issues, e.g. anything involving "Sema"confirmedVerified by a second partyconstexprAnything related to constant evaluationdiverges-from:edgDoes the clang frontend diverge from edg compiler on this issuediverges-from:gccDoes the clang frontend diverge from gcc on this issuediverges-from:msvcDoes the clang frontend diverge from msvc on this issue

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions