size = (unsigned)(expression);
? The contradiction is stark. If a variable deserves the name `size` it deserves the type `size_t` as well. size = (unsigned)(expression);
? The contradiction is stark. If a variable deserves the name `size` it deserves the type `size_t` as well. size_t v; //64-bit size_t
v = (unsigned)0xff00000001;
printf("%zu\n", v); //Prints 1
I don't get any warnings for this on GCC 9.4 or Clang 15.0.4 with Wall+Wextra.If you wanted to deliberately do that kind of cast, for some reason, you could prevent the warning like this:
v = (size_t)(unsigned)0xff00000001;A LOT of code just shouldn’t be C or C++.
Like for example if I'm writing an interpreter that runs on devices with limited memory size_t might be bigger than I need for the length of a buffer in user code, and using a shorter integer might be a useful optimization.
This is really an example where you have a sharp tool and need training/oversight/experience to use it safely. And even with those things, mistakes happen. The same is true of power tools as memory unsafe systems code.
Your optimization is a good example for something where jumping through explicit hoops would not only be palpable, but even help signify the intent of your code optimization, while protecting common code from nasty surprises.
Otherwise, we could also go back to earlier C days and, for example, let the compiler be silent about assigning a pointer of the wrong type without an explicit cast. That makes sense a lot of times, but still I want the compiler to tell me that I passed a struct foo* where a struct bar* was needed, or worse, a struct foo**.
What I'd rather see are better lints and a better culture around them instead of the cowboy attitude you see in a lot of systems code. Today, lints for C are pretty bad and the default attitude isn't to fix warnings but to disable them when compiling the software. Even worse is when distro maintainers patch the sketchy code instead of the 1p devs doing it right from the beginning.
It doesn't matter what your warnings are if the attitude is to ignore them. And in this case, there are several warnings that would tell you the code smells and needs attention.
That would be a mistake since size_t is poorly designed - it’s unsigned and you should use signed integer types whenever possible in C, as the Google C++ style guide says.
This is more secure because UBSan is more likely to find bugs using it. Bit unfortunate the STL doesn’t like you doing it.