[Given a bit-counting function that takes an unsigned int or unsigned
long parameter...]
If the intention is to call the function from either signed or unsigned
int, then the code will not work on non-2s complement machiens for
signed ints.
Well, that depends on what one *wants*.
Say for example you have -0 on a sign-mag or 1s comp. machine in an int
variable y:
Even though the y is not devoid of set bits on those machines, once the
call is made to the function and the variable is converted from signed
-> unsigned, C's rules will whipe out all the set bits (via -0 +
UINT_MAX + 1). Your function will return 0 as the # of set bits
because of the conversion that took place on the argument before
function entry.
Indeed it will. And yet, on such a machine, if -0 is produced by
ordinary arithmetic (as opposed to being used to detect uninitialized
variables, for instance), C requires that x==y be true even if x
is -0 and y is +0. That is:
x = <expression 1>;
y = <expression 2>;
if (x == y && bitcount(x) != bitcount(y))
puts("how peculiar!");
should never print the message, even if x is -0 and y is +0. So
you might *want* bitcount() to return 0 in both cases.
On the other hand, if you want to inspect the representation,
rather than the value, of a variable, you can still write that:
int representational_bit_count(unsigned char *p, int size);
#define RBC(var) \
representational_bit_count((unsigned char *)&(var), sizeof(var))
...
if (x == y && RBC(x) != RBC(y))
puts("while x==y, their representations differ");
Note, however, that two identical and nonnegative values can still
have differing representations, if some of the bits in the
representations are padding bits.
This is an example of C's bias towards 2's complement
machines (which is understandable because 2's complement is the "best"
way to represent negative integers!).
While *I* am biased towards 2'sC
I am not so sure C really is.
C gives you the ability to inspect representations (via pointers
and "unsigned char *"); it is up to you, the programmer, not to
abuse it.