I am learning "Expert C Programming" by Peter Van Der Linden. In chapter A.6, the writter described how to determine whether a variable is unsigned or not in K&R C.The macro is below:
#define ISUNSIGNED(a) (a>=0 && ~a>=0)
The book is very old, it was first published in 1994! And I have not learned K&R C before. The question is that how to determine whether a variable is unsigned or not in ANSI C.
I have tried to solve the problem like this. Since "0" is int in ANSI C, and any other number except float, double and long double will be converted to int or unsigned int by Integer Upgrade when compare with 0. So I want to find an edge between unsigned and signed number. When I compare (the edge type)0 with a, the type of a will not be changed. The macro also the model is below:
#define ISUNSIGNED(a) (a>=(the edge type)0 && ~a>=(the edge type)0)
I can not find the edge type, is there anybody can help me solve the problem? I have changed "number" to "variable" for more accurate expression.
The term "unsigned" in computer programming indicates a variable that can hold only positive numbers. The term "signed" in computer code indicates that a variable can hold negative and positive values.
The int type in C is a signed integer, which means it can represent both negative and positive numbers. This is in contrast to an unsigned integer (which can be used by declaring a variable unsigned int), which can only represent positive numbers.
In C, unsigned is also one data type in which is a variable type of int this data type can hold zero and positive numbers. There is also a signed int data type in which it is a variable type of int data type that can hold negative, zero, and positive numbers.
C and C++ are unusual amongst languages nowadays in making a distinction between signed and unsigned integers. An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative.
For anyone coming to this question but not restricted to C89 (technically C11 is also ANSI C because ANSI has ratified it):
#include <stdio.h>
#include <limits.h>
#define ISSIGNED(x) _Generic((x), \
unsigned char: 0, \
unsigned short: 0, \
unsigned int: 0, \
unsigned long: 0, \
unsigned long long: 0, \
signed char: 1, \
signed short: 1, \
signed int: 1, \
signed long: 1, \
signed long long: 1, \
char: (CHAR_MIN < 0) \
)
int main()
{
char x;
printf("%d\n", ISSIGNED(x));
}
#define ISUNSIGNED(a) (a>=0 && ((a=~a)>=0 ? (a=~a, 1) : (a=~a, 0)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With