Samir Raut wrote:In this small program I was expecting the output to be 11. Since there is y = x and later x has a new value assigned. Why is it 5? Can someone explain it to me? What it the fundamentals behind it?
Line 5. X=5. And Y have yet to be declared.
Line 6. X=5, so Y=5.
Line 7. X=11. And Y remains unchanged (still equal 5).
The transitive property doesn't apply in programming - at least, not across distinct lines of code.
mathematically, you may thing that
y = x
x = 11
y = x = 11
But that's not now programs work. When you write
int x = 5
you get a hunk of memory that can hold a value. You can refer to it with the variable name "x", and you store the value 5 in it.
You then write
int y = x;
you get ANOTHER hunk of memory that can hold a value. You can refer to it with the variable name "y", and you store the value in it that is stored in the memory you refer to by "x". So now, you have two hunks of memory, and each holds the value 5.
when you then say
x = 11
you are saying "change the value in that first memory hunk to now hold the value 11". This does nothing to what's stored in that second chunk.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors