r/cpp • u/comfortcube • Aug 29 '26
Might have found a (tiny, nuisance) bug in g++ 16.2.1 and -Wconversion?
I am far from presuming myself a compiler expert, and no this was not AI, I promise. I'm simply a long-time user of gcc/g++, and it's not everyday I am confident enough that a bug is not in my code but with the tool, haha. I'm pretty warning-sensitive so this kind of thing catches my attention. Wondering if I'm missing something, so asking it here first.
g++ version: g++ (GCC) 16.2.1 20260819 (Red Hat 16.2.1-2) (I'm on Fedora 44)
C++20
Given lines like this:
std::uint16_t count = 0;
// int other_var set elsewhere
count += ; // <-- -Wconversion flags this
specifically, the warning is:
| ;
-Wconversion /w either -O0 and -O3 (my usual build optimization lvls to catch optimization-dependent warnings), this gets flagged.
Well, the result of a boolean expression is 0 or 1, so obviously, there should not be a conversion. Even with the accumulate op here and integer promotion, there shouldn't be a warning (you can do count += 1 or count++ and it definitely doesn't flag -Wconversion). And more notably, the below code doesn't get flagged:
std::uint16_t count = 0;
// int other_var set elsewhere
bool match = ;
count += match;
I also noted that clang with -Wconversion and the same optimization lvls does not flag this. I also know I've done this before in C with other versions of gcc and don't get flagged with this.
So, am I missing something or am I right to suspect this is a possible bug with at least my version of g++?
19
u/ezoe Aug 29 '26
GCC manual said
https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wconversion
Meaning, it doesn't warn ALL implicit conversions. It warns ONLY IF it "may alter a value"
Given that, bool to std::uint16_t conversion never alter a value. The values of bool is either 0 or 1. Both can be expressed without a possibility of altering a value by std::uint16_t.
26
u/TheRealSmolt Aug 29 '26
I think the standard defined implicit
boolconversion is tointspecifically. That's how I read cppreference, at least. I wouldn't call this a bug, though it is an interesting regression if what you are saying about the versions is true.5
u/sheckey Aug 29 '26
I know it’s not your point, and your point is revealing notable conversion issues (that are new to me, so thank you) but I have never really liked these kind of logic-as-computation statements, even back in the K&R days. I always have to mentally decode them. I prefer “if (match) ++count”. You have reminded me again to watch out for this kind of thing in our ancient code base. Thanks!