Skip to content

[clang] Structure binding (destructuring assignment) does not generate "unused variable" warning when one variable remains unused #58953

@alexandrustinov

Description

@alexandrustinov

We need a function which returns structure Result with some value and error code, kind of Go language style error handling (see https://go.dev/doc/tutorial/handle-errors for reference).
The result need to be handled using destructuring assignment, C++17 feature (see https://en.cppreference.com/w/cpp/language/structured_binding)

Actual behavior: compiler does not generate warning if error code is not handled, it generates warning when both value and error variable are unused only, considering them as "single variable" [value, error], while those are supposed to be handled as separate variables.

Expected behavior: Compiler should generate warning when either value or error variable is unused. For our case the calling function must handle the result error code before processing the result value. If the error handling is omitted then compiler should notify about that.

#include <stdio.h>

struct Result {
    int value;
    int error;
};

Result func(int arg) {
    if (arg) {
        return {arg, 0};
    }
    else {
        return {0, -1}; // -1 means faulure here
    }
}

int main() {
    auto [value, error] = func(0); // simulating faulure

//    if (!error) // we forgot to handle error code, compiler should generate warning about unused variable, but it does not
        printf("value = %d", value);

}

// clang++ --std=c++17 -Wunused-variable unused_destructure.cpp

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzerenhancementImproving things as opposed to bug fixing, e.g. new or missing feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions