[Bug c++/126756] New: Too many -Wsign-conversion warnings with bitwise NOT operator ~
rdiez-2006 at rd10 dot de via Gcc-bugs <[email protected]>
| Newsgroups | gmane.comp.gcc.bugs |
|---|---|
| Message-ID | <[email protected]/bugzilla/> |
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=126756
Bug ID: 126756
Summary: Too many -Wsign-conversion warnings with bitwise NOT
operator ~
Product: gcc
Version: 16.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: rdiez-2006 at rd10 dot de
Target Milestone: ---
I have become accustomed to -Wsign-conversion in order to prevent bugs.
The trouble is, it is too noisy in my opinion, which discourages its usage.
Here is a test program which illustrates the noise:
// Compile with "g++ -Wsign-conversion".
#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
template< typename IntegerType >
constexpr IntegerType InvertBits ( const IntegerType v ) throw()
{
// Why no warning here? It is converting from int to uint8_t too.
return ~v;
}
int main ()
{
const uint8_t BYTE_CONSTANT = 1;
// warning: unsigned conversion from 'int' to 'uint8_t' {aka 'unsigned char'}
changes value from '-2' to '254' [-Wsign-conversion]
const uint8_t INVERTED_BYTE_CONSTANT = ~BYTE_CONSTANT;
// Prints 0xFE, which is correct.
printf( "INVERTED_BYTE_CONSTANT: 0x%02" PRIX8 "\n", INVERTED_BYTE_CONSTANT );
uint8_t value;
value = 0;
// warning: unsigned conversion from 'int' to 'uint8_t' {aka 'unsigned char'}
changes the value of '-2' [-Wsign-conversion]
value |= ~BYTE_CONSTANT;
// Prints 0xFE, which is correct.
printf( "value: 0x%02" PRIX8 "\n", value );
value = 0;
// warning: unsigned conversion from ‘int’ to ‘uint8_t’ {aka ‘unsigned char’}
changes value from ‘-1’ to ‘255’ [-Wsign-conversion]
value |= ~value;
// Prints 0xFF, which is correct.
printf( "value: 0x%02" PRIX8 "\n", value );
value = 0;
// No warning here.
value = ~value;
// Prints 0xFF, which is correct.
printf( "value: 0x%02" PRIX8 "\n", value );
// No compilation warning, even though it is conceptually the same.
value = InvertBits( BYTE_CONSTANT );
// Prints 0xFE, which is correct.
printf( "value: 0x%02" PRIX8 "\n", value );
value = 0;
// No compilation warning, even though it is conceptually the same.
value |= InvertBits( BYTE_CONSTANT );
// Prints 0xFE, which is correct.
printf( "value: 0x%02" PRIX8 "\n", value );
return 0;
}
I think GCC should suppress the warnings above, as the intent is clear.
But let's assume for a moment that the warnings should stay. Then why is the
template function above not generating them? It is conceptually the same.
I think that GCC is suppressing the warnings in some situations, but not in
others. The question is whether those heuristics could be extended to the
common scenarios shown above, without risking too much.