Thursday, March 22, 2007

An Obvious Mistake

class MyClass
private void Sample()
int i=10;
int i=20;

Will this code compile?
Obviously it wouldn't!!

But why wouldn't it compile?
Obviously because i has multiple declarations!!

But what is not so obvious is the reason behind not allowing multiple declarations. To talk about those not so obvious reasons, first of all one basic point. What happens when you say int i=10?

4 bytes of memory gets allocated, 10 is stored in it and the identifier 'i' points to it. Simple!

Now let's say we do multiple declarations for i, like in the above program. int i=10 allocates 4 bytes of memory and i points to it. Then we have int i=20. Another 4 bytes is allocated, 20 stored in it and, again, identifier 'i' points to this new memory. So when you use 'i' again anywhere, the compiler or runtime doesn't know which chunk of memory you are trying to reference to! Hence, undesired results!

This is the not so obvious reason for the program not compiling!

No comments: