M
Martin Wells
I commonly use the likes of -1 for max unsigned values, or something
like -7 to get 6 away from the max value; sort of like:
unsigned x = ...
if (-7 == x) puts("x is 6 away from its maximum");
Since I rarely use anything smaller than int, this has never been a
problem. Obviously though, there'd be a problem if I tried:
char unsigned x = ...
if (-7 == x) puts("x is 6 away...
The reason there'd be a problem is that x could be promoted to a
SIGNED int.
So I'm wondering... what's the handiest way of checking this for any
unsigned integer expression?
In the case of unsigned char, we can do
if ((char unsigned)-7 == x)
Similarly in the case of unsigned short, we can do
if ((short unsigned)-7) == x)
But what I'm looking for is a universal method. My first thoughts were
something like
#define MAX(expr) ( (expr) * (char_unsigned)0 - (char
unsigned)1 )
The problem with this of course though is that, even though we have
the casts, everything will still get promoted to int (either signed or
unsigned depending on INT_MAX).
Anyone got any ideas such that I can write universal code such as?:
if (MAX(x)-6 == x) puts("x is 6 away from its maximum");
If we had a typeof operator it would probably be something like:
#define MAX(expr) ( (typeof expr)-1 )
I have the likes of "-1 == x" littered throughout my code... and yes
it works fine... but I'd like something more sustainable just in case
I'd choose to use something smaller than an int.
Martin
like -7 to get 6 away from the max value; sort of like:
unsigned x = ...
if (-7 == x) puts("x is 6 away from its maximum");
Since I rarely use anything smaller than int, this has never been a
problem. Obviously though, there'd be a problem if I tried:
char unsigned x = ...
if (-7 == x) puts("x is 6 away...
The reason there'd be a problem is that x could be promoted to a
SIGNED int.
So I'm wondering... what's the handiest way of checking this for any
unsigned integer expression?
In the case of unsigned char, we can do
if ((char unsigned)-7 == x)
Similarly in the case of unsigned short, we can do
if ((short unsigned)-7) == x)
But what I'm looking for is a universal method. My first thoughts were
something like
#define MAX(expr) ( (expr) * (char_unsigned)0 - (char
unsigned)1 )
The problem with this of course though is that, even though we have
the casts, everything will still get promoted to int (either signed or
unsigned depending on INT_MAX).
Anyone got any ideas such that I can write universal code such as?:
if (MAX(x)-6 == x) puts("x is 6 away from its maximum");
If we had a typeof operator it would probably be something like:
#define MAX(expr) ( (typeof expr)-1 )
I have the likes of "-1 == x" littered throughout my code... and yes
it works fine... but I'd like something more sustainable just in case
I'd choose to use something smaller than an int.
Martin