Ticket #184 (closed defect: invalid)

Opened 6 years ago

Last modified 6 years ago

range behaves in an odd way with unsigned types

Reported by: dagss Owned by: robertwb
Priority: critical Milestone: 0.11
Component: Code Generation Keywords:
Cc:

Description

I was just bitten by this:

cdef unsigned i = 10
print range(-i, i)
for x in range(-i, i):
    print "entered"

This will print out an empty list, and not enter the loop. This is odd, considered that

def f(int a, int b):
    print a, b

cdef unsigned i
i = 10
f(-i, i)

will print out -10, 10.

Change History

Changed 6 years ago by dagss

Apologies if this is fixed in 0.11 already. I've got to run now but I'll try to remember to check that later.

Changed 6 years ago by dagss

Confirmed on 0.11 and added testcase going into the various cases. This might be wanted behaviour, but I find it very unintuitive myself.

 http://hg.cython.org/cython-devel/rev/fc5f285a50f6

Changed 6 years ago by dagss

To be clear, c_call succeeds in that testcase, and the rest fails.

Changed 6 years ago by dagss

  • summary changed from range behaves oddly with unsigned types to range behaves in an odd way with unsigned types

Changed 6 years ago by robertwb

I believe this is the correct behavior--arithmetic (including subtraction and negation) on unsigned values yields unsigned values in C. The pitfalls are no more or different than what one encounters in C, and inconsistency is probably worse than unintuitive behavior. Imagine

cdef unsigned int i = 10
print -i, i, -i < i

which would give (were we to change Cython's interpretation)

-10 10 False

Playing around with this will possibly mess up anyone trying to do bit-fiddling and stuff too. Anyone using unsigned types has to explicitly declare them as such, and there's little benifit to using them most of the time. They are better thought of as arithmatic mod 2^n for some n. There should probably be a big warning in the section on numpy indexing about the pitfals of using unsigned types.

I would mark this as invalid.

Changed 6 years ago by dagss

In C the arguments are always typed, so you don't encounter this problem in practice. I.e. this example prints -10, 10. I see that there's no obvious behaviour when it comes to coercion to Python objects that would make this easier to use though.

#include <stdio.h>

void f(int a, int b) {
  printf("%d %d\n", a, b);
}

int main() {
  unsigned i = 10;
  f(-i, i);
}

Changed 6 years ago by dagss

  • status changed from new to closed
  • resolution set to invalid

OK, marking as invalid, proposing something else on the mailing list.

Changed 6 years ago by robertwb

  • status changed from closed to reopened
  • resolution invalid deleted

Changed 6 years ago by robertwb

  • owner changed from somebody to robertwb
  • status changed from reopened to new

Changed 6 years ago by robertwb

  • status changed from new to closed
  • resolution set to invalid
Note: See TracTickets for help on using tickets.