Simple question on declaring a variable

  • Thread starter Thread starter Dom
  • Start date Start date
D

Dom

I should know this, but I don't. In the following, is an integer
being created with each iteration?

for (...)
{
int n = SomeFunction ();
}

Or should I do the following, even if I don't plan to use "n" outside
the loop?

int n;
for (...)
{
n = SomeFunction ();
}
 
Hi,


--
Ignacio Machin
http://www.laceupsolutions.com
Mobile & warehouse Solutions.
Dom said:
I should know this, but I don't. In the following, is an integer
being created with each iteration?

No, only 1 position in reserved in memory for the variable.

for (...)
{
int n = SomeFunction ();
}

Or should I do the following, even if I don't plan to use "n" outside
the loop?

You will have the same memory comsuption in both cases. but they are not the
same!
In this second case the variable can be referenced outside the for loop. In
the first case n only exist inside the loop.
 
In the general case it makes no difference and compiles to the same
thing. I would use the first syntax just to limit the scope.

Caveat: if the variable is "captured" inside an anonymous method (or
lambda in C# 3), then note that then lifetime and separation relates
to the code-block which declares it; but you don't seem to be doing
that here...

Marc
 
Dom said:
I should know this, but I don't. In the following, is an integer
being created with each iteration?

for (...)
{
int n = SomeFunction ();
}

Or should I do the following, even if I don't plan to use "n" outside
the loop?

int n;
for (...)
{
n = SomeFunction ();
}

It does not matter functionally, but I would recommend the first,
because it limits the scope of n.

Arne
 
It does not matter functionally, but I would recommend the first,
because it limits the scope of n.

Not disagreeing with you, but it's worth emphasising that as Marc said,
it *does* matter in more complex code where the variable is captured.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top