My first assumption on seeing such a statement (in the absence of your
explanation) would be that the programmer didn't know C very well, and
mistakenly thought that the cast was necessary, or perhaps that the
cast was added just to silence a warning.
That's fine. Both of those things still communicate the essential
facts, which is that the programmer knew that the conversion would
occur and intended it.
Since "j=q;" and "j=(unsigned)q;" (given the above declarations) mean
exactly the thing, a compiler could conceivably warn about both of
them, or just about the version with the cast.
Why would it warn about the cast? No compiler warns about that cast --
it does exactly what the programmer obviously expected. The problem
with "j=q;" is that there is no way to know that the programmer
*intended* the conversion.
If you have any large, complex project and run without conversion
warnings enabled, enable them sometime. If you find, say, 300
warnings, I will bet you that at least 1/4 of them will be cases where
you didn't realize a cast was involved. The vast majority of those, of
course, will be safe.
The best way to make it clear that you know the conversion is safe is
to add a comment: /* This conversion is safe. */.
Comments should only be used where it's either not possible or
significantly inferior to make the code self-commenting. In this case,
the cast makes the code self-commenting. So unless you have a case
where the cast is significantly inferior, it's preferable to cast than
comment. Another advantage is that automated testing tools are much
more likely to understand the cast than the comment.
I agree that that's the biggest advantage, but it's not the only one.
I presume you meant disadvantage. And I agree. This is not always
unequivocally better. Some warnings can only be silenced with code so
ugly you would be wise to live with the warning instead.
FWIW, I just took a 190,000 line commercially-deployed, well-audited
application and spent an hour analyzing conversion warnings. There
were 1,396 conversion warnings and I analyzed about 250 of them. Of
them, the vast majority (90% or so) were obviously harmless.
Quite a few of them (15 or so) revealed aspects of the code that were
clearly not thought about, but turned out to be safe. These required
some changes to ensure the code was completely solid. Adding a cast
was not sensible here, as it would suggest we know the cast is safe.
But I don't believe any of my changes on these would have any actual
effects on the code's operation.
There were six actual bugs, most nearly harmless. (Which probably
explains why they weren't caught.)
The one that had the most obvious serious consequence caused an
incorrect call to 'posix_fadvise' claiming random access (rather than
the intended sequential) for files that are part of an FTP-like file
transfer system. I believe this will, at least on some OSes, disable
read ahead.
Catching six bugs an hour in well-audited, deployed code is pretty
darn good.
DS