value of variable did not reset!

I got a function that assign a to 1 if it is 0, but when I call it again, a is already 1. I thought once it exits the function, all the variables in it would reset, isn't that how it is for other languages? What is going on?

#include <iostream>

using namespace std;

void hi(){
int a;
cout << a;
if(!a){
a = 1;
}


}

int main()
{
hi();
hi();

return 0;
}
You haven't initialised variable a before you use it, so behaviour is undefined.

It becomes undefined every time you call the function.

I imagine that all languages would say the same, some more loudly than others.

Try using 'static' (to retain values between calls) and initialising it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

void hi()
{
    static int a = 1;
    cout << a;
    if( !a ) a = 1;
    else     a = 0;
}

int main()
{
   hi();
   hi();
   hi();
   hi();
}
Last edited on
I thought once it exits the function, all the variables in it would reset
No. In C++, local variables are are not initialized unless their type has a constructor. So every time you enter hi(), the variable a has an undefined value.

Put another way, local variables are not normally preserved between calls to the function. If you want to preserve the value, you must add static before the declaration (as lastchance mentioned)
Topic archived. No new replies allowed.