+ 1
C++ for loop variable
Hello. im pretty new in C++ and struggle to read variables from a for loop outside the loop. example: int a; for(int x; x<10; x++){ if(×==5){ a = 1; } ........ } if(a == 1){ do smth } the second if will never start because i cant read my variable "a", or the for loop doesnt set my "a" to 1. What can i do to accomplish that? is it even possible? I hope my question is understandable. Good day to everyone!
7 Antworten
+ 3
Luckily, both the problem and it's solution are simple:
You need to give your variables an initial value, like 0.
If you don't, they'll start with a random value (whatever there was at that point in memory before).
So x might start out as 6. Then you never reach x==5.
+ 2
In my opinion, you set first value x = 1 or x = 0 in for loop
+ 1
thanks for you answers. i just noticed i made a mistake in my example "code", sorry for that.
here is the corrected one:
int a = 0;
for(int x = 0; x < 10 ; x++){
if(x == 5){
a = 1;
break;
}
......
}
if(a==1){
do smth
}
what i have observed is, that the variable "a" will always stay 0 and thus the second "if" doesnt work. And it seems to me that i cant write a variable outside the for loop. or am i missing something?
thanks again for your help guys
+ 1
Not sure when you observed so, but the code works fine for me:
https://code.sololearn.com/coFnKukDDDyI/?ref=app
As long as a variable is visible inside the current scope, you can operate on it. For example, 'x' is declared inside the loop and therefore only local to the scope of the loop. Accessing it outside would result in an error.
'a', however, is declared in the outer scope of, say, main(), and thus usable everywhere inside it, including both inside and outside of the loop.
More on scopes:
https://en.cppreference.com/w/cpp/language/scope
https://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm
https://www.geeksforgeeks.org/scope-of-variables-in-c/
0
thanks a lot for your answer. that is exactly how i expected it to work. that means i made a different mistake. i test it out later again.