I was looking at one of the questions in SO, and looked at the question.
Why id function behaves differently with integer and float?
I tried that in python to get the same id for both a&b. But when i tried the same on c,
main()
{
int a=4,b;
b=2+2;
printf("%p\n",&a);
printf("%p",&b);
}
But this printed different values. Why is the difference ?
3 Answers 3
The equivalent Python code works for the reason given in several answers in the question you link - Python (or, at least, CPython) happens to cache some small integer values - 4 is among them, and so every Python integer object that equates to 4 will be the same object, and hence have the same id.
In C, integers are mutable, so a compiler can't perform this kind of optimisation - if you increment a, you would not expect b to change If Python integers were mutable, the ids of a and b in the equivalent code would likewise be different.
At the implementation level, int means a different thing to C than it does to Python - even if they happen to serve the same purpose in a program.
Comments
Python caches some small integers. From python documentation http://docs.python.org/2/c-api/int.html
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)
Comments
In C two variables will always have different addresses,
The only exception is when you use union,
Consider the code given below,
union x
{
int a;
int b;
}y;
main()
{
y.a=4;
y.b=2+2;
printf("%p\n",&y.a);
printf("%p",&y.b);
}
Here both y.a and y.b will point to the same address.
&a == &b? After all, you're dealing with variables. Maybe if you use optimization, but after all both variables are indicating available memory space which are completely independent from each other.&ais the address ofa. Their values are the same however their memory addresses are different.