hi all:
I just met a peice of code using such a type casting :
how to understand this.Code:if(to->sin_addr.s_addr != (unsigned)-1){ strcpy(hnamebuf, av[0]); hostname = hnamebuf; }
hi all:
I just met a peice of code using such a type casting :
how to understand this.Code:if(to->sin_addr.s_addr != (unsigned)-1){ strcpy(hnamebuf, av[0]); hostname = hnamebuf; }
type casting allows you to convert from one type to another.
In this case you're changing the way the compiler interprets the -1, which is a signed int by default. You're instructing the compiler to treat it as an unsigned value. i.e. as the largest value an int can hold.
I'm guessing that in an error case all bits of s_addr are set to 1, which is is equivalent to -1 for an unsigned int.
QuantumPete
Last edited by QuantumPete; 06-11-2008 at 04:37 AM. Reason: Removed those poor singed ints.
"No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
"Have you tried turning it off and on again?" - The IT Crowd
thank you QuantumPete!
This is assuming a two's compliment number system right? So it may not be entirely portable, although should work on anything built since I started writing code.You're instructing the compiler to treat it as an unsigned value. i.e. as the largest value an int can hold.
Yes it does. And yes it should work on anything that isn't about to get a government old-age pension... ;-) [Although, if the spec defines that the value is -1 under error condition, rather than all ones, then it's fine even on a ones complement machine].
And I think the cast is there to silence a compiler warning rather than anything else. The warning could also be bypassad by suffixing the number with a U.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.