variable declaration in a for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

16th Jul 2022, 8:47 AM
Кавун 🍉
Кавун 🍉 - avatar
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.
16th Jul 2022, 9:02 AM
Jayakrishna 🇮🇳
+ 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
16th Jul 2022, 8:57 AM
A S Raghuvanshi
A S Raghuvanshi - avatar