Liste des Groupes | Revenir à cl c |
On 29/10/2024 11:13, David Brown wrote:Well, there is already a syntax standardised for use for this kind of thing - attributes. For example, marking a function declaration with [[noreturn]] will turn off any warnings about the function failing to return. Attributes are specifically for such additional information to improve the compiler's knowledge (for the purposes of optimisation and/or static error checking) without affecting the semantics of the code.On 29/10/2024 13:21, Thiago Adams wrote:As I said,On 29/10/2024 09:16, Thiago Adams wrote:>
>
Edit to fix the sample
>
// Here we acknowledge the truncation
void f(int i) {
...
const unsigned char c = i; [[!truncation]];
}
>
>
// Warning: there is no truncation to acknowledge.
void f(unsigned char i) {
...
const unsigned char c = i; [[!truncation]];
}
>
This should give you what you are asking for, if I have understood you correctly:
>
#define truncate(type, value) \
_Generic((value), \
type : (void) 0, \
default : (type) value \
)
>
>
>
// OK
void f1(int i) {
const auto c = truncate(unsigned char, i);
}
>
// Error
void f1(unsigned char i) {
const auto c = truncate(unsigned char, i);
}
>
>
I am not at all convinced this is a good idea. I am /certainly/ not convinced "truncate" is a good name - the general term, AFAIK, for a conversion that might try to squeeze a large value into a smaller type is "narrowing" rather than "truncating".
>
You could expand the idea further and have a "truncate" macro that checks for bounds at run time or compile time (I'd make use of the gcc extension __builtin_constant_p here, but there may be a fully standard way to do this).
>
>
>(I intend to show a general idea. There are likely better examples.)
My objective was to show the concept of "warning acknowledge".
Name and syntax weren't important.
The solution for truncate you are proposing maybe is valid, but it is for the specific case.
I think it is valid to think is specific cases and I can find more samples.
maybe if (condition) where the condition is constant expressions.
Les messages affichés proviennent d'usenet.