Okay here's a real deal. I tried to answer these questions. However I'm not sure if I am correct. I would appreciate feedback from C experts.
Consider an ANSI compliant compiler on a machine using 2?s complement arithmetic for integers. The task is
to figure out whether a variable used for integers is signed or not.
One suggested solution is to write a macro like the following:
#define IS_UNSIGNED( var ) ( (var) >= 0 && ~(var) >= 0 )
(a) Will this macro work for all possible integer values or are there any exceptions? (If you find any exceptions,
you are encouraged to find a solution that will get rid of those exceptions.)
Answer: The macro will not work for anything but 0. The solution is to change the equality in the second comparison
#define IS_UNSIGNED( var ) ( (var) >= 0 && ~(var) <= 0 ) //This should work for all numbers
(b) If the variable is a type instead of a variable, how would the macro above be rewritten?
Answer:
#define IS_UNSIGNED( TYPE ) (((type) (-1)) > ((type) 0))
Analysis: If the type is unsigned (type)(-1) will be greater than 0 otherwise, it will be less than 0.
(c) Is it possible to write a function to do this job instead of a macro? If yes, show how the the macro shown
above can be rewritten as a function. If it cannot be cast as a function, explain why not. [Either write below,
the IsVarUnsigned( ... ) function or give your reasoning.]
Answer:
I'm not sure about this.