Comparing an unknown type against a negative value

115 views Asked by At

I have a variable id whose type may vary from platform to platform. In several places, existing code (which I cannot change) sets the id to a "negative" value, e.g.

id = -ETIMEDOUT;

On some platforms, id might be signed; on others, it may be unsigned. I want to test to see if the id was set to -ETIMEDOUT. The naive attempt below subtly fails when id is unsigned:

if(id == -ETIMEDOUT)

How do I concisely test for this condition?

2

There are 2 answers

3
nonsensickle On BEST ANSWER

@jlahd has posted a good answer. I would like to offer an alternative though.

if (id == (typeof(id)) -ETIMEDOUT)

I think that this will do similar but there is a problem with it. It isn't in the C standard and is a GCC extension.

You can read a little more about it here

Verbatim quote of @rici's comment:

Since you probably know some typedef which works as the type of id, you can presumably do this without typeof, although that is cleaner. However, it should be

(typeof(id))(-ETIMEDOUT) 

(the parentheses around -ETIMEDOUT are just cosmetic but the unary minus is required.) Alternatively, the following should be pretty well foolproof:

if (-id == ETIMEDOUT)

since if id is signed, that obviously works; if id is unsigned, then unary minus has well-defined behaviour.

7
jlahd On

Try this:

id += ETIMEDOUT;
if(id == 0) { /* timed out */ }
id -= ETIMEDOUT; /* if you need to keep id untouched */