AFAIK most compilers by default will output a warning in this case.
typedef struct {
unsigned value : 4;
} S;
void foo(S* s, unsigned value) {
// error: conversion from 'unsigned int' to 'unsigned char:4' may change value
s->value = value;
}
I mean, I guess I can see the rationale.. it's just annoying to have to resort to using pragmas to turn off -Wconversion whenever I need to assign to a bitfield. #include "stddef.h"
short foo(short a) { return a % 42; }
size_t bar(void) {
size_t sz = ~0UL;
return foo(sz);
}
https://godbolt.org/z/3ec9v8Pa4Personally I have never seen gcc spitting out a false positive. IMO it's always a good idea to explicitly downcast even if you know that it's 'safe'. That way someone else will see instantly what's going on. The fact that Rust requires it should tell us something.
You can find more cases in the bugtracker. To be fair, it seems many of them were fixed in recent releases.
warning C4267: 'argument': conversion from 'size_t' to 'short', possible loss of data
https://godbolt.org/z/nYeWT7zv6 (/W3 is the default warning level when creating a new project)I saw these warnings so often that I assumed that every compiler had them.