+ 1
variable declaration in a for loop
why do you need to declare a variable 2 times and why if you remove the comments there will be an error? https://code.sololearn.com/cm6JpSoPi6I8/?ref=app
2 Answers
+ 5
Read about variable scopes.
The variable i declared in a block, here in loop has local scope and only available in that block. Automatically deleted after the block or loop. So can't exist outside loop.
Try to see : declare variable before loop and exist in total main() function. You can use same in both loops.. Because it's local variable then to main() function.
Declare outside main, will have a global scope which exist to all functions within a c file.
+ 4
Because of its scope if u use for loop with single statement your value will be show define for single statement to avoid this issue use curly bracket your commented line says your variable is undefined it omits your loop scope or define i variable globally