Re: Pass value of short type
From: Howard (alicebt_at_hotmail.com)
Date: 06/28/04
- Next message: Howard: "Re: Struct and inheritance"
- Previous message: Howard: "Re: not sure how to create the main for this program"
- In reply to: JKop: "Re: Pass value of short type"
- Next in thread: Old Wolf: "Re: Pass value of short type"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 28 Jun 2004 15:44:09 GMT
"JKop" <NULL@NULL.NULL> wrote in message
news:h7xDc.3281$Z14.4370@news.indigo.ie...
> Busin posted:
>
> > In the code below, should i be casted to "unsigned int" type first
before
> > passing it into f()? Thanks!
> >
> > void f(unsigned int);
> >
> > int main()
> > {
> > unsigned short i;
> > i = 23;
> > /* Should i be casted to "unsigned int" type first before passing it
> > into f()? */
> > f(static_cast<unsigned int>(i))
> > }
>
> That's what I myself call an implicit conversion, ie. you don't have to
> explicitly specify that it is to be converted. Consider:
>
> unsigned char snake = 12;
>
> unsigned long int lizard = 4000000000UL;
>
> snake = lizard;
>
>
> You may be thinking here, Oh No! There's not enough room in that unsigned
> char for that number! You may be tempted to write:
>
> snake = (unsigned char)lizard;
>
> But it's unneccesary. It's done "automatically", "implicitly". The
unsigned
> long int number is truncated, most likely from 4000000000 to 255, for
> storage in the unsigned char.
>
Well, in general, that's going to be a bad thing, isn't it? You just lost
some data. The compiler should warn you about doing that, until you add the
cast, which makes the warning go away and makes you think you're safe, which
you might not be. (You might have needed that data!)
In the OP's question, there was no loss of data. You can always put an
unsigned short into an unsigned int, with no need for casting. There will
be no warning, because the data will always fit.
In the OP's case, the implicit conversion is a promotion from unsigned short
to unsigned int, which is different from trying to stick a long into a char.
> My suggestion to you is just try to compile your code without any casts.
If
> it compiles, then all is fine and dandy. If it doesn't, *THEN* you can go
> playing with casts.
>
I agree you should avoid casts whenever possible (and especially avoid
C-style casts in C++). But just because it compiles, don't assume it works.
Heed compiler warnings, especially in cases where you might lose data!
-Howard
- Next message: Howard: "Re: Struct and inheritance"
- Previous message: Howard: "Re: not sure how to create the main for this program"
- In reply to: JKop: "Re: Pass value of short type"
- Next in thread: Old Wolf: "Re: Pass value of short type"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|