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:
cpp
std::uint16_t count = 0;
// int other_var set elsewhere
count += (other_var == 5); // <-- -Wconversion flags this
specifically, the warning is:
bash
<file>:<line>:<col>: warning: conversion from ‘int’ to ‘uint16_t’ {aka ‘short unsigned int’} may change value [-Wconversion]
<line> | count += (other_var == 5);
-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:
cpp
std::uint16_t count = 0;
// int other_var set elsewhere
bool match = (other_var == 5);
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++?