0

Can anyone explain why x didn't assigned to zero at the time of 2nd calling??

#include <iostream> using namespace std; class a { public : void func() { static int x = 0; /* x is initialized only once across three calls of func() and the variable will get incremented three times after these calls. The final value of x will be 3. */ x++; cout<<x; // outputs the value of x }}; int main() { a a1; a1. func(); a1. func(); a1. func (); return 0; }

3rd Sep 2017, 8:42 AM
Harsha Sanju
Harsha Sanju - avatar
6 Respostas
+ 10
Because class object x is declared static, which means that there is only one copy of x for all instances of the class. Declaring a new instance of the class or calling the same method will not result in x being re-initialized.
3rd Sep 2017, 8:52 AM
Hatsy Rei
Hatsy Rei - avatar
+ 8
I guess the output will be 123 x is not re-initialized as 0 because x has been declared as static.
3rd Sep 2017, 8:52 AM
Shamima Yasmin
Shamima Yasmin - avatar
+ 8
@Shamima I ran it. Yes it was 123
3rd Sep 2017, 8:54 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 6
Output please?
3rd Sep 2017, 8:45 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
hi, if u declare the variable static then it will remember the previous value of that variable which will be used for next operation. if u want to reinitialize the value then remove the static keyword.
3rd Sep 2017, 12:01 PM
Nanda Balakrishnan
0
thank u for this guys
3rd Sep 2017, 11:06 AM
Harsha Sanju
Harsha Sanju - avatar