In C++, value scope is important for declaring variables. If a variable is declared in a for loop, it is different than if it is announced in the main() function. If the variable is declared in the for loop, it will only be present in the loop. In the main() loop, though, it will be able to be used everywhere in the function.
Example:
#include <iostream>
using namespace std;
int main()
{
int a = 0;
for (int x = 0; x < 1; x++)
{
a++;
}
cout << a;
}
The code above doesn’t give an error, so it is correct. But the one below isn’t because the variable was declared in the wrong scope:
#include <iostream>
using namespace std;
int main()
{
for (int x = 0; x < 1; x++)
{
int a = 0;
a++;
}
cout << a;
}
// program doesn't work because 'a' was declared in the wrong scope.