Can I write simply
for (int i = 0; ...
instead of
int i;
for (i = 0; ...
in C or C++?
(And will variable i
be accessible inside the loop only?)
Can I write simply
for (int i = 0; ...
instead of
int i;
for (i = 0; ...
in C or C++?
(And will variable i
be accessible inside the loop only?)
Yes, it's legal in C++ and in C99.
Yes.
Depends on the compiler and its' version. AFAIK, in modern compilers i is accessible inside of the loop only. Some older compilers allowed i to be accessible outside of loop as well. Some compilers allow i to be accessed outside of the loop and warn you about non-standard behavior.
I think (but I'm not sure about it), that "i outside of the loop" was used somewhere in VC98 (Visual Studio 6, which AFAIK, also had a globally defined "i" variable somewhere that could lead to an extremely interesting behavior). I think that (microsoft) compilers made somewhere around around 2000..2003 started printing "non standard extensions used" for using i outside of loop, and eventually this functionality disappeared completely. It isn't present in visual studio 2008.
This is probably happened according to a standard but I cannot give a link or citation at the moment.
It's perfectly legal to do this in C99 or C++:
and its
while
equivalent is:Acutally
for(int i=0;i<somevalue;i++)
was always drilled into me as the preferred way to define a for loop in c and c++.As far as "i" only being accessible in your loop, you have to be care about the variable names you use. If you declare "i" as a variable outside of the loop and are using it for something else then you are going to cause a problem when using that same variable for a loop counter.
For example:
will be automatically changed when you hit the for loop and declare i=0
Its valid in C++
It was not legal in the original version of C.
But was adopted as part of C in C99 (when some C++ features were sort of back ported to C)
Using gcc
The variable is valid inside the for statement and the statement that is looped over. If this is a block statement then it is valid for the whole of the block.
if you use variable out side the loop it will be change every time when you initialize it inside loop
now i value will change every time