Ok, easy question.
Not caring about the variable scope what is better (i.e. possibly in
memory allocation etc)
Have you read what you posted carefully? Does it really represent the
question you wanted to ask?
int someVar=0;
for (int i=0;i<1000;i++)
{
...
someVar++;
...
}
In the example above, someVar will take on the values of 1 through
1000 on successive iterations of the loop.
OR
for (int i=0;i<1000;i++)
{
...
int someVar=0;
someVar++;
...
}
In the example above, someVar will always be 0 at the point where it
is defined and initialized, and always 1 after the post increment
expression. It will never take on the values 2 through 1000, no
matter how many times the loop executed.
Or it really doesnt make any difference at all?
If this were real code, it certainly would make a difference.
In principle, a variable defined inside a block is created when
execution reaches the line that defines it, and is destroyed when
control reaches the end of the block or leaves the block.
If a variable defined inside a loop is a type with a non-trivial
constructor and destructor, each of these will be called for each
iteration of the loop. If the object is a primitive built-in type,
and perhaps even a POD structure or class type, the compiler may
generate code to allocate the memory once and reuse it each time, or
it may decide to allocate and deallocate the memory by some method in
each iteration of the loop. There is no requirement or guarantee
either way.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq