Best search algorithm to find condition within a range

Chris Angelico rosuav at gmail.com
Thu Apr 9 18:36:36 CEST 2015


On Fri, Apr 10, 2015 at 2:15 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Fri, 10 Apr 2015 01:34 am, Chris Angelico wrote:
>
>> It's equally impossible for the addition of two positive signed
>> integers to result in a negative integer.
>
> Why oh why do C programmers tell such porkies??? *semi-wink*
>
> [steve at ando c]$ gcc add.c
> [steve at ando c]$ ./a.out
> a = 1
> b = 2147483647
> a+b = -2147483648
>
>
> Looks like a negative integer to me, but then, given that its undefined
> behaviour, perhaps the compiler flipped some pixels on the screen so it
> merely *looks* negative.

Precisely. Another compiler, or another CPU architecture, is welcome
to behave differently. *According to the C standard*, you just did
something impossible, so it's equally valid for the output to be 5, 3,
7, or 25, all of which would probably be produced by Princess Ida's
compiler. (Mind you, her compiler might do that when asked to add 2
and 2, so I'm not sure it's all that helpful a comparison. [1])

> Here's the source code:
>
> [steve at ando c]$ cat add.c
>   a = 1;
>   b = 2147483647;
>   printf("a+b = %d\n", a+b);

The first undefined part here is that this operation might not even
overflow. If the compiler uses a 64-bit int, this will simply produce
2147483648. But even assuming that it can't represent that total in a
signed int, there's nothing in the spec that says it has to become
negative.

ChrisA

[1] http://diamond.boisestate.edu/gas/princess_ida/webop/pi_10d.html



More information about the Python-list mailing list