Skip to content

[clang-tidy] False positive bugprone-non-zero-enum-to-bool-conversion with custom operator #65315

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

Closed
chrchr-github opened this issue Sep 5, 2023 · 3 comments · Fixed by #65498
Assignees
Labels
clang-tidy false-positive Warning fires when it should not

Comments

@chrchr-github
Copy link

enum E {
    E0 = 0x1,
    E1 = 0x2,
    E2 = 0x4
};

E operator&(E a, E b) { return static_cast<E>(a & b); }

void f(E e) {
    if (e & E1) {}
}
<[source>:10:9: warning: conversion of 'E' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-non-zero-enum-to-bool-conversion]
   10 |     if (e & E1) {}
      |         ^
[<source>:1:6: note: enum is defined here]
    1 | enum E {
      |      ^

https://godbolt.org/z/nv3PxYdM7

@llvmbot
Copy link
Member

llvmbot commented Sep 5, 2023

@llvm/issue-subscribers-clang-tidy

@PiotrZSL
Copy link
Member

PiotrZSL commented Sep 5, 2023

From check documentation:

May produce false positives if the enum is used to store other values (used as a bit-mask or zero-initialized on purpose). To deal with them, // NOLINT or casting first to the underlying type before casting to bool can be used.

But I agree that this specific case probably could be excluded on check level.
Expect this to be fixed in Clang-tidy 18 timeframe.

@PiotrZSL PiotrZSL self-assigned this Sep 5, 2023
@PiotrZSL PiotrZSL added false-positive Warning fires when it should not and removed new issue labels Sep 5, 2023
@HerrCai0907
Copy link
Contributor

Do you think it will be better instead of treating this case as fake positive?

using E_BitMap = uint32_t;
enum E {
    E0 = 0x1,
    E1 = 0x2,
    E2 = 0x4
};

E_BitMap operator&(E a, E b) { return static_cast<E_BitMap>(a & b); }

void f(E e) {
    if (e & E1) {}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment