pete142 said:
When I compile this code:
typedef unsigned char BYTE;
BYTE *
IpString(unsigned int ip)
{
static BYTE ipString[4];
ipString[0] = (BYTE) 0xff & (ip >> 24);
Make sure type 'unsigned int' on your system is at least
24 bits wide. The language only requires 16.
s/24/25/, else shifting by 24 bits is undefined.
ipString[1] = (BYTE) 0xff & (ip >> 16);
ipString[2] = (BYTE) 0xff & (ip >> 8);
ipString[3] = (BYTE) 0xff & ip;
return ipString;
}
for every assignment statement, I get the warning: "conversion from
'unsigned int ' to 'unsigned char ', possible loss of data."
How can I get rid of these four warnings?
First, make sure there will indeed be no data lost (i.e.
the value will fit into an 'unsigned char'), or that if
it is, it doesn't matter to your program.
Observe that each `&' produces a value in the range 0..255,
guaranteed to fit in `unsigned char'.
Then you can
use a cast. E.g.:
ipString[3] = (BYTE) (0xff & ip);
Use casts with caution. They will often inhibit compiler
warnings that can notify you of things you need to know.
-Mike
Thanks, Mike. I've done all that you suggested. I am using the
strictest warnings level, and should be able to get a clean, no-
warnings compile out of this code /without/ reducing the warnings
level.
So how can I get rid of these warnings, please? That is, how can I
convince the compiler (using standard-C mechanisms) that I don't need
to be warned about these productions?
Are you sure you rearranged the casts in the way Mike Wahler
illustrated? That is, do they now apply to the entire `&' result
instead of just to the first term? If you've done this correctly
and the compiler is still whining, you may simply have to live
with it: Compilers are allowed to issue all the warnings they like
for whatever capricious reasons strike their fancy, and there is
no guaranteed way to shut them up one hundred percent of the time.
File a bug report with the compiler vendor if you like, but don't
expect a fix in the next five minutes.
If the compiler simply won't stop whining and if you are
absolutely sure its complaint is irrelevant, you should at least
insert a comment explaining why the warnings can be ignored:
/* NOTE: Frobozz Magic C version 2.41-06 warns about
* possible data loss in the next four assignments.
* All the "loss" is in fact intentional and caused
* by AND-ing with 0xff, so FMC is a Nervous Nellie.
* -- pete142, 08-Apr-2007
*/
(This comment is rather verbose, but brevity is not the important
point here. You need to provide *all* the relevant information:
Which compiler, which version, what the complaint is about, why
the complaint can be ignored, who says so, and when the analysis
was made. All this will be invaluable to the poor slob who, a
year and a half from now, starts getting warnings when trying to
port the code to SadistiC on the DeathStation 9000.)