Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a C/C++ program, can you define a global variable that is not accessible by a certain function?

Tags:

c++11

Can we define a function as such in C or C++ where a certain function cannot access it?

like image 380
kotAPI Avatar asked Dec 11 '25 05:12

kotAPI


1 Answers

C/C++ offers you two types of global variables, although many people will probably say that static variables are not global variables...

Now, you can achieve that if you define the global variable after said function. This may not be practical, especially if the variable is defined in a header file because in that case you have to define that function before the #include which may not or even is not likely to be possible.

Now, static variables are specific to the .c or .c++ file where they are defined and often are not viewed as global variables, but they are since they are unique in your program. Static variables can be defined in a separate file making them inaccessible to other functions in other files. (remember that a static variable in C++ is a variable defined inside a namespace without a name.)

In C++, you can also define a variable member that's static. This means the variable is global, but you can make it a private variable. To protect it further, you can define it in a sub-class as a private member. However, either way you'll probably need to gain some form of access to that variable (otherwise it's useless) and thus add functions that return a pointer, a reference, or the current value of that variable...

like image 139
Alexis Wilke Avatar answered Dec 13 '25 00:12

Alexis Wilke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!