Question about math.pi is mutable

Christian Gollwitzer auriocus at gmx.de
Fri Nov 6 14:59:57 EST 2015


Am 06.11.15 um 20:40 schrieb Chris Angelico:
> On Sat, Nov 7, 2015 at 6:30 AM, Bartc <bc at freeuk.com> wrote:
>> Is there no way then in Python to declare:
>>
>>     pi = 3.141519     # etc
>>
>> and make it impossible to override?
>
> Nope. Even in C++, where classes can define certain things as const,
> private, and other such restrictions, you can always get around them
> by manipulating pointers appropriately.

No, that is not right. If you cast away the constness from a pointer to 
a constant, you can technically write to that memory, but the behaviour 
is undefined - another way of saying that the program is illegal.

In many cases, the compiler will inline the constant - because you 
promised, that it can't change - and the update to the constant will not 
change in all parts of the program:


apfelkiste:Tests chris$ cat constub.cpp
#include <iostream>

void call_by_ref(const double &v) {
	std::cout<<"In function: v="<<v<<std::endl;
}

int main() {
	const double pi=3.14;
	double *errptr = const_cast<double*>(&pi);
	*errptr= 0.0;
	std::cout<<"Now pi is "<<pi<<std::endl;

	call_by_ref(pi);
	return 0;
}
apfelkiste:Tests chris$ g++ constub.cpp
apfelkiste:Tests chris$ ./a.out
Now pi is 3.14
In function: v=0


	Christian






More information about the Python-list mailing list