How's this code is working?.. Is it using ++i as i outside the main function after static variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How's this code is working?.. Is it using ++i as i outside the main function after static variable?

https://code.sololearn.com/cunxMrCLmpRl/?ref=app

21st Mar 2022, 6:46 PM
proGAMBLER
proGAMBLER - avatar
5 Answers
+ 2
No. The static variable created only once. And it persists it's value through out the program. A normal local variable scope is limited to function. When you come out of loop then local variable is removed from memory. But static variable, not removed and retains it's previous value in various function calls. So first call to foo() makes I=1 2nd call makes it I= 2 3rd call make it I= 3 So it retaining previous function call value. A constant value can't be changed after you declared but static variables can be changed it's value.. Hope it helps...
21st Mar 2022, 7:10 PM
Jayakrishna 🇮🇳
+ 1
Oh I got it..If we don't use static here,output will be 111.Value is not changing because variable is getting destroyed after each iteration of function. Thanks
21st Mar 2022, 7:18 PM
proGAMBLER
proGAMBLER - avatar
+ 1
Yes. You're welcome..
21st Mar 2022, 7:19 PM
Jayakrishna 🇮🇳
0
static variables are declared only once in entire scope of program. So it retains its value between function calls. And won't create new one like normal variable. it calls 3 times foo() function in for loop.
21st Mar 2022, 6:49 PM
Jayakrishna 🇮🇳
0
you mean whenever function is called,static variable having i will be 0 ?Am I right ..Then what is difference between constant and static variable?
21st Mar 2022, 6:53 PM
proGAMBLER
proGAMBLER - avatar