#include <iostream>
#include <conio.h>
int crnt_value = 0;
int bigger_by_one()
{
crnt_value++;
return crnt_value;
}
int main()
{
int first = bigger_by_one();
int second = bigger_by_one();
printf("%d, %d", first, second);
_getch();
return 0;
}
Is there a way to make crnt_value accessible only to bigger_by_one()?
Is there a way to make crnt_value accessible only to bigger_by_one()?
Easy-peasy, initialize a static variable in your function before you increment it. Each time the function is called the previous value is used instead of the initial value.
#include <iostream>
int bigger_by_one();
int main()
{
int first = bigger_by_one();
int second = bigger_by_one();
int third = bigger_by_one();
std::cout << first << ' ' << second << ' '
<< third << ' '
<< bigger_by_one() << '\n';
}
int bigger_by_one()
{
staticint crnt_value = 0;
crnt_value++;
return crnt_value;
}
"crnt_value" is defined in the function "bigger_by_one" there for it has local scope to that function. Nothing else can see that variable and after it is returned it is destroyed until the next time you call the function and it is created again.
FYI if you are writing a C program leave out the C++ header files like "iostream". Also in the "bigger_by_one" function you could just write return ++crnt_value; would work the same.
Hope that helps,
Andy
Edit: My bad I totally missed this one. I did not see the global variable or I would have told you to define it in the function. As a global the whole file has access to it.