I hope you thought the below answer:
if (Var >0 )
signed
else
un-signed.
If so, your answer is wrong. Because, once more check the question carefully. It is not asking variable value is signed/ signed or negative/ postive. It is asking type's sign.
Example, type 'char' it has both 'sighed char' and 'unsigned char'. How do we know? Thanks to the 2's complement, using which we can find it.
Before saying the way, let me explain that, we cant use function for this: why? because if we use function, the type of the variable is defined, but our purpose is to find for any given type. So, we use Macro for it.
If we use macro, we can find the sign type, in two cases:
If the argument is value: (thanks to 2's complement)
#define IS_SIGNED(__VAR__) ( ( __VAR__ > 0 ) && ( ~__VAR__ > 0 ) )
If the argument is type: (thanks to typecasting)
#define IS_SIGNED(__TYPE__) ( (__TYPE__)0 - 1 > 0 )
PS: This question is asked in a interivew for recruiting to Microsoft.
1 comment:
Should this macro not be IS_UNSIGNED instead of IS_SIGNED
Post a Comment