Verifiably better, validated Enum for Python

Steve D'Aprano steve+python at pearwood.info
Fri May 26 07:46:50 EDT 2017


On Thu, 25 May 2017 11:26 am, Chris Angelico wrote:

> On Thu, May 25, 2017 at 9:34 AM, bartc <bc at freeuk.com> wrote:
>> That was quite likely with older Fortrans, where subroutines only used
>> pass-by-reference, but which didn't stop you passing references to
>> constants that the subroutine could then modify.
>>
>> I doubt that's still the case. With C, however, I tried this today:
>>
>>   "abcdef"[3] = 'z';
>>   puts("abcdef");
>>
>> Some versions crashed; some printed 'abczef', and some 'abcdef'. (The
>> language says this is undefined, but it doesn't try too hard to stop you
>> doing it.)
> 
> And why should they try to stop you? The whole point of undefined
> behaviour is that you shouldn't be doing this, so if you do, the
> interpreter's allowed to do anything.

Does the C specification actually refer to this as undefined? I'm not a C
expert, but it seems to me that it is defined as an error. I tried
compiling that code:


[steve at ando c]$ cat stringassign.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  "abcdef"[3] = 'z';
  puts("abcdef");
  return 0;
}
[steve at ando c]$ gcc stringassign.c
stringassign.c: In function ‘main’:
stringassign.c:6: error: assignment of read-only location


but I couldn't get it to succeed.


> # Lifted from reddit: change the value of 29 to be 100

[snip ctypes abomination]

> What's going to happen? Will it print 100 twice? What is y? The
> behaviour of CPython after you mess around with ctypes like this is as
> undefined as any of C's weirdnesses.

It actually isn't. CPython's behaviour is merely implementation dependent.


> And yes, Steve, this is a challenge to you: if you think C's undefined
> behaviour is an abomination that should not be allowed to exist,

CPython doesn't have to define the behaviour here. In *that* sense, the
ordinary, regular sense, it is undefined. The implication of that is that
whatever happens will happen according to some deterministic but
unpredictable (to you, the developer, at least) chain of cause and effect
that depends on the implementation. Probably something bad.

That's fine. The Python language does not have to define the behaviour of
programs which abuse ctypes like that. If you do so, then whatever happens
will happen.

That's not how the C standard defines "undefined behaviour", or the
implication of such.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list