[Pyrex] precedence differences - GOTCHA!

David McNab david at rebirthing.co.nz
Mon Oct 1 00:01:22 CEST 2007


Hi,

I've just spent 3 hours hunting down a weird bug.

Initially, I had some C code within a Pyrex method. This was working. 

But then, I moved the code into a separate C function in a C source
file, calling it from within my Pyrex method, so I could optimise the
pointer arithmetic with idioms like '*buf++ = fred'.

And then, my code started producing weird results then segfaulting.

It was only when I compared the Pyrex-generated code with the C code
that I noticed the subtle difference.

In my pyrex code, I have:

    if x & 1 == 1:
       ...

In my C function, I hand-converted this to:

    if (x & 1 == 1) {
       ...
    }

The reason why the Pyrex version worked, and the C version didn't, was
because of differences in operator precedence between C and Python.

When Pyrex generates the C code, it correctly translates:

    x & 1 == 1

to:

    ((x & 1) == 1)

because it honours the Python operator precedence.

But in C, the '==' comparison operator trumps the '&' bitwise operator,
while in Python, it's the other way around. Hence the difference.

Oh, YAFL! :P
Hope it helps others to avoid this trivial pitfall.

Cheers
David






More information about the Pyrex mailing list