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; }
6 odpowiedzi
+ 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.
+ 8
I guess the output will be 123
x is not re-initialized as 0 because x has been declared as static.
+ 8
@Shamima I ran it. Yes it was 123
+ 6
Output please?
+ 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.
0
thank u for this guys