lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mon, Jul 08, 2013 at 06:24:21PM -0400, Jay Carlson wrote:
> On Jul 8, 2013 9:15 AM, "Roberto Ierusalimschy" <roberto@inf.puc-rio.br>
> wrote:
> 
> [signed integer overflow]
> 
> > > > That may not do what is expected, because it involves
> > > > implementation-defined behavior:
> > > >
> > > > 3.2.1.2 Signed and unsigned integers [...]  When an integer is
> > > > demoted to a signed integer with smaller size, or an unsigned
> > > > integer is converted to its corresponding signed integer, if the
> > > > value cannot be represented the result is implementation-defined.
> > >
> > > If I remember right, you can work around this with a memcpy() from the
> > > unsigned variable to the signed variable.
> >
> > Before trying to solve a problem, let us be sure there is a
> > problem.
> 
> Yes. What problem is wrapping on signed integer overflow trying to solve?

I think the idea is to follow in Java's footsteps, where you use signed
integers but specify a twos-complement representation so people who need
64-bit unsigned arithmetic 64-bit bitwise operators can make do--as long as
they're careful and don't pass unsigned values to routines which care about
sign (e.g. string.sub).

But I'm confused by the code:

static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
                                                   lua_Integer v2) {
  switch (op) {
    case LUA_OPADD: return intop(+, v1, v2);
    case LUA_OPSUB:return intop(-, v1, v2);
    case LUA_OPMUL:return intop(*, v1, v2);
  ...

where intop is

  #define intop(op,v1,v2) \
        cast_integer(cast_unsigned(v1) op cast_unsigned(v2))

Why even bother with the explicit conversions? If you're relying on
two's-complement behavior, it's unnecessary. If you're not, it's
insufficient. Am I missing something?