Bug 105581 - new warning about boolean types and relational operators
Summary: new warning about boolean types and relational operators
Status: UNCONFIRMED
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 12.0
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: diagnostic
Depends on:
Blocks: new-warning, new_warning
  Show dependency treegraph
 
Reported: 2022-05-12 10:11 UTC by David Binderman
Modified: 2022-10-27 06:45 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description David Binderman 2022-05-12 10:11:03 UTC
For this C code:

void g( int );

void f( bool a, bool b)
{
	if (a < b)
		g( 1);
}

recent gcc doesn't find a problem:

$ /home/dcb/gcc/results/bin/gcc -c -g -O2 -Wall -Wextra -pedantic may12a.cc
$

Here is cppcheck complaining:

$ /home/dcb/cppcheck/trunk.git/cppcheck --enable=all may12a.cc
may12a.cc:6:8: style: Comparison of a variable having boolean value using relational (<, >, <= or >=) operator. [comparisonOfBoolWithBoolError]
 if (a < b)
       ^
$

There is an example in the gcc source code:

trunk.git/gcc/sreal.h:72:25: style: Comparison of a variable having boolean value using relational (<, >, <= or >=) operator. [comparisonOfBoolWithBoolError]

Source code is

        return negative > other_negative;
Comment 1 Andrew Pinski 2022-05-12 10:23:00 UTC
Well. There is a meaning for the code though.
That is negative > other_negative
Means negative is true while other_negative is false the result will be true which is exactly what it is testing here.
Comment 2 Andreas Schwab 2022-05-12 10:46:30 UTC
Equivalent to negative && !other_negative.
Comment 3 David Binderman 2022-05-12 11:49:45 UTC
(In reply to Andrew Pinski from comment #1)
> Well. There is a meaning for the code though.
> That is negative > other_negative
> Means negative is true while other_negative is false the result will be true
> which is exactly what it is testing here.

In abstract, false and true can't be compared with "<".

In the implementation choice of false as 0 and true as 1, then relying
on the implementation values does make "<" valid.

I think that's the bad style cppcheck is complaining about. It's just
better style to have it as a logical expression, as Andreas shows.
Comment 4 Andreas Schwab 2022-05-12 12:12:05 UTC
There is nothing abstractly wrong with ordering false and true.
Comment 5 Andrew Pinski 2022-10-27 06:45:26 UTC
This is just a style issue really ...