Re: Catching the unsigned int



Aandi Inston wrote:
> Here's the problem: I have a macro which is called all over a large
> program, and which will produce incorrect results if the argument is
> an unsigned [long] int.
>
> (It didn't originally, but an external header file changed).
>
> What I was trying to do was catch this, by (for test purposes)
> changing the macro and forcing a compiler error or warning if used
> with an unsigned long int, rather than long int. This is proving
> more challenging than I expected.
>
> I tried
>
> #undef THEMACRO
> #define THEMACRO(x) CallProc(&x)
> long int CallProc ( long int *x) ;

If you invoke THEMACRO(x) on an x which is not a long int lvalue
you violate a constraint. So the solution is for you to crank up
your error/warning levels.

> (Which gives a few errors on things that aren't lvalues but I can
> live with that).

Given the apparent purpose of the macro, why are you (presumably)
passing rvalues to it?

> But it seems that (in this environment) I get no error if THEMACRO
> is used for an unsigned int.
>
> The code can be compiled in Microsoft Visual C++ or Metrowerks
> CodeWarrior; as C or C++ language. (Setting up to compile with
> another compiler would probably take more manually checking all
> references, which this lazy programmer is trying to avoid).
>
> (Background: the macro used to do x<<16 but now does
> x < -32767 ? BAD_RESULT : x << 16.

So there is no function CallProc? If that's so, then you should not
have posting your earlier version. How about you show us the _real_
code you're using, rather than something which is almost but not
quite totally unlike the real code.

Note that left shifting signed integers is fraught with undefined
behaviour.

> So far as I can tell the effect of feeding this an unsigned int is
> that the -32767 is treated as unsigned before doing the comparison.)

Yes, that's because the arithmetic promotions require that an operation
between an unsigned int and an int invoke a promotion of the int to
unsigned int.

Show us the macro you actually have, and how you intend to use it.
Show us the invocation of the macro which is causing problems.
In other words, give us code, not descriptions.

--
Peter

.



Relevant Pages