From 820d6ac9d7c2743e6804914471159a1ca74cbd41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20v=2E=20L=C3=B6wis?= Date: Wed, 4 Oct 2006 05:47:34 +0000 Subject: [PATCH] Fix integer negation and absolute value to not rely on undefined behaviour of the C compiler anymore. Will backport to 2.5 and 2.4. --- Lib/test/test_builtin.py | 1 + Misc/NEWS | 3 +++ Objects/intobject.c | 7 +++---- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index ca7a8f38c0b..f3bdbe29c4f 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -116,6 +116,7 @@ class BuiltinTest(unittest.TestCase): self.assertEqual(abs(0), 0) self.assertEqual(abs(1234), 1234) self.assertEqual(abs(-1234), 1234) + self.assertTrue(abs(-sys.maxint-1) > 0) # float self.assertEqual(abs(0.0), 0.0) self.assertEqual(abs(3.14), 3.14) diff --git a/Misc/NEWS b/Misc/NEWS index 0001f9f1b71..2fb0793f8d8 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -12,6 +12,9 @@ What's New in Python 2.6 alpha 1? Core and builtins ----------------- +- Integer negation and absolute value were fixed to not rely + on undefined behaviour of the C compiler anymore. + - Bug #1566800: make sure that EnvironmentError can be called with any number of arguments, as was the case in Python 2.4. diff --git a/Objects/intobject.c b/Objects/intobject.c index cbca49524ee..4e1f04f2429 100644 --- a/Objects/intobject.c +++ b/Objects/intobject.c @@ -754,10 +754,9 @@ int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z) static PyObject * int_neg(PyIntObject *v) { - register long a, x; + register long a; a = v->ob_ival; - x = -a; - if (a < 0 && x < 0) { + if (a < 0 && (unsigned long)a == 0-(unsigned long)a) { PyObject *o = PyLong_FromLong(a); if (o != NULL) { PyObject *result = PyNumber_Negative(o); @@ -766,7 +765,7 @@ int_neg(PyIntObject *v) } return NULL; } - return PyInt_FromLong(x); + return PyInt_FromLong(-a); } static PyObject *