How to get warnings for implicit conversion to bool in simple return statement from clang or clang-tidy

Viewed 292

The question is how to get a warning for using = by mistake when == is intended.

The warning -Wparentheses gives warnings when implicitly converting the result of an assignment to a bool value in certain contexts. However, for a function that is just a simple return statement, that warning is triggered in gcc but not in clang.

In the following example, if written explicitly (-DEXPLICIT) both clang and gcc gives a warning, but for the shorter return *x = *y; gcc gives a warning (with -std=c99 -Wall) but clang does not.

#include <stdio.h>
#include <stdbool.h>

bool is_equal(int *x, int *y)
{
#ifdef EXPLICIT
    if(*x = *y) return true;
    else return false;
#else
    return *x = *y;
#endif
}

int main()
{
    int foo = 17;
    int bar = 42;

    bool b = is_equal(&foo, &bar);

    printf("%d %s %d\n", foo, (b?" == ":" != "), bar);
}

(Here, the intended result of is_equal is an equality test, so the assignment is a bug. Please note that this is a minimal example: for a simple equality test the pointers should be const and thus catch the accidental assignment, but in the actual code that motivated this question they couldn't be.)

I also hoped that the clang-tidy check readability-implicit-bool-conversion would trigger, but it doesn't.

(Update: Clang gives no warning (related to this) with -Weverything, but can I get clang-tidy to warn about this?)

Is there a way to get clang or clang-tidy to warn for this int-to-bool conversion?

I know it is not "dangerous" in the sense that it is well-defined and portable and that it may be common in existing code, but it is still a potential bug I want to be able to check for.

1 Answers

*x = *y: I think you wanted this to be an equality check, but it is currently an assignment. Change it to *x == *y, here if(*x = *y) return true; and here return *x = *y;.

I would also recommend changing the function signature to bool is_equal(const int *x, const int *y) to make it clear that the function shall not change the inputs.

Related