Is it possible to make a variable that is only accessible to certain functions?

If I want for example, make a function that returns a value bigger by 1 each time it's being used, like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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()?
closed account (E0p9LyTq)
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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()
{
   static int crnt_value = 0;

   crnt_value++;

   return crnt_value;
}

1 2 3 4

http://en.cppreference.com/w/cpp/language/storage_duration
Hello Dvir Arazi,

Welcome to the forum.

"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.
Last edited on
Thanks, FurryGuy!
If only I knew it was that simple.
closed account (E0p9LyTq)
If only I knew it was that simple.

Now you know it is simple. :D

If you are satisfied your question has been answered, please "mark as solved." :)
Topic archived. No new replies allowed.