Reputation: 341
#include<stdio.h>
int main(void)
{
int x,y;
x=10;
y=x;
x=5;
printf("x=%d,y=%d\n",x,y);
return 0;
}
Output: x=5,y=10
So can we say that y
is immutable?
Upvotes: 0
Views: 1233
Reputation: 34638
Except const
, all the variables values are mutable in C
.
So can we say that y is immutable?
The short answer: No.
Upvotes: 1
Reputation: 882048
So can we say that
y
is immutable?
We can, but we'd be wrong :-)
You only have to experiment a little to find this out. A simple y = 42
would suggest that y
were not immutable but there is still some doubt in that it may have created a new value and pointed y
at that, leaving the old value untouched.
This can be discounted with code like:
int y = 7; // we have a y
int *pY = &y; // and a pointer to it
y = 42; // change y
printf ("%d %d\n", y, *pY);
You'll see there that both methods used to access y
get the new value, indicating that the underlying value of y
itself has changed, rather than having a new value created and y
somehow redirected to it.
That's not to say C itself doesn't have immutable data, that's really what the const
keyword is all about. However, that's rather different to Python's concept of immutability.
Upvotes: 0