Sujet : Re: constexpr keyword is unnecessary
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.cDate : 29. Oct 2024, 13:16:52
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vfqjnk$1hos6$1@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
User-Agent : Mozilla Thunderbird
On 29/10/2024 02:04, Kaz Kylheku wrote:
On 2024-10-28, Thiago Adams <thiago.adams@gmail.com> wrote:
I believe warnings in code should be treated as alarms that require
acknowledgment.
>
For instance,
>
const unsigned char ch = 1234;
>
GCC:
warning: unsigned conversion from 'int' to 'unsigned char' changes value
from '1234' to '210' [-Woverflow]
>
The programmer might intend this behavior; in that case, the "alarm"
should be acknowledged.
>
I would like a portable (standardized) way to achieve this.
For conversion warnings, that portable way should ideally be a cast.
Any half-decent compiler should shut up if the conversion is
explicitly requested:
const unsigned char ch = (unsigned char) 1234;
If not, complain to the compiler developer.
It works this way for conversions that are constraint violations,
like between unlike pointers. Assign a pointer to a variable of
the wrong type, and there is a required diagnostic. With a cast,
the diagnostic is not required, and it would be irksome if there
still were one.
Yes, in this case, using a cast is the way to go with current compilers.
But, the concept of "alarm acknowledgment" removes a specific warning that must exist. It can be a safer alternative.
(I intend to show a general idea. There are likely better examples.)
Consider this function:
void f(int i) {
...
const unsigned char c = (unsigned char)i;
}
If someone changes the type of `i` to `unsigned char`, then the cast becomes unnecessary:
void f(unsigned char ch) {
...
const unsigned char c = (unsigned char)ch;
}
With the "alarm acknowledgment" idea (I'll just invent a syntax `[[!truncation]]`), we would get a warning if there is no actual truncation to acknowledge. For example:
void f(unsigned char ch) {
...
const unsigned char c = (unsigned char)ch; [[!truncation]];
// Warning: there is no truncation to acknowledge.
}
The way GCC/Clang works today, we can disable some warning using pragma.
#pragma CAKE diagnostic push
#pragma CAKE diagnostic ignored "-Wenum-conversion"
...
...
#pragma CAKE diagnostic pop
The code represented by "..." may change, which could cause the warning to disappear, making any ignored "-Wenum-conversion" directive unnecessary noise. Additionally, we could mistakenly disable more warnings than initially intended.
So the "alarm acknowledgment" can be a safer complement for the language.