+ 1
What is the difference between assigning a value to a for loop in "()" and out of the "()"?
When I do this: i=3; a=2; for(;i<=500;i++) { for(;a<=500;a++) { } } it sometimes doesn't work. I mean I am not getting anything as output. But when I do this: for(i=3;i<=500;i++) { for(a=3;a<=500;a++) { } } Ä°t is properly working. What is the difference?
5 Answers
+ 19
First off, SL compiler is restricted for conserving its resources as much as possible by limiting the number of loop cycles that your program would run. You can check that out by running the following code.
#include <iostream>
int main() {
for(int i = 0; i <= 1000; i++)
std::cout << i << "Done.\n;
}
Next thing is, after the first completion of inner for loop for 500 or so times, a's value becomes 501 before returning the program flow to the outer for loop to continuing the next 500 times. At this point, since a's initialization is outside of the for loop, and a can't be reset to start its job all over again, program flow skips the inner for loop for the rest of the program. (a value is still 501 and the condition says 501 <= 500, so it breaks the loop)
In some cases though, it would be nice to declare your index outside the loop and then initialize it inside the loop. As an example see the following snippet.
int i;
int n = 10;
int m = 20;
for(i = 0; i < n; i++)
{
// Do stuff...
}
// ...
for(i = 0; i < m; i++)
{
// Do another thing...
}
If you had the additional question feel free and ask.
+ 18
I've been a university student in CS field 4 years ago. But I didn't learn much in there because of their inferior teaching methodologies. After graduation I began to focus seriously on programming and English learning (Since I wasn't able to fully understand English programming books or articles) . It was difficult to teaching myself programming and English at the same time but I did it in a hard way and it was worth it.
I encourage you to do the same thing if you are serious about that.
+ 6
Aside from the fact that they are inner loops (causing the inner loop to not be reset after outer loop is finished an itteration), declaring the variable outside the loop enlarges its scope. It is a common practice to keep variables in the smallest scope possible unless there's a reason for it to be enlarged.
Here's some info on that since I'm lazy:
https://stackoverflow.com/questions/7959573/declaring-variables-inside-loops-good-practice-or-bad-practice
+ 3
Thank you @Babak. By the way where did you learn C and C++ programming?
+ 2
Thank you @Rrestoring.