x1 is accessible outside the current source file. x2 is not.
x3 is a local variable that's initialized each time foo() is called. x4 is only visible inside foo(), but it lasts from the first time foo() is called until the end of the program.
I'm not certain that x5 and x6 are legal C++ because of the way the are initialized, but I think x5 is a member of struct A: each instance of A has it's own instance of x5. There is only one instance of x6 and it is accessible from within struct A (or via A::x6).
Another question. I don't want variable with this value. I don't want it occupy my memory (even if this variable is only four bytes). I need only value by itself for something like this
1 2 3 4 5 6 7
int foo()
{
char buf[128];
for (int i = 0; i < 128; i++) buf[i] = f1();
for (int i = 0; i < 128; i++) f2(buf[i]);
...
}
Here i use "128" many times. I want define it only once. What is preferrable for next?
1 2 3 4 5 6 7
int foo()
{
char buf[size];
for (int i = 0; i < size; i++) buf[i] = f1();
for (int i = 0; i < size; i++) f2(buf[i]);
...
}
1) #define size 128
2) constint size = 128;
3) staticconstint size = 128;
AFAIK using #define is not "the c++ way".
x1 is not internal. Its external. On phone so explanation later if no one else provides one.
Well, this is one of those differences between C and C++. In C, x1 would be considered extern. Learn something everyday... Surprised I've not run into this before.
I guess in the end, it would be good practice to always explicitly label your variables' linkage type.
3.5.3
A name having namespace scope (3.3.6) has internal linkage if it is the name of
— a variable, function or function template that is explicitly declared static; or,
— a variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage; or
— a data member of an anonymous union.
const variables are usually optimised away by vompiler as long as you do not take its address. If you want to guarantee this, use constexpr