"memory is no longer a problem nowadays"
That is a fallacy. If it were true we would never close a program in life.
Even if you don’t want to overdo it, you still have many reasons to save memory. Memory is slow, so there are cache levels in processors. Each level is faster, but it also has smaller capacity. The faster cache has something like 64KB and it hasn’t changed for a long time. Is that enough memory? The more memory you waste the more chance something is not in the cache and therefore there will be performance loss.
One thing I always say is that people drop sentences without explaining why. They usually say that this is "good practice," which is a great way to "sell an idea" that makes no sense or that the person does not dominate.
So every time someone claims something and doesn’t say why, ignore it, ask why and go and search other sources to see if it makes sense. But you have to choose the sources and it’s not common for people to know how to do that because when she knows she no longer needs to search.
This case is tragic because you find a lot, but a lot of people saying it. And a lot of experienced people. Only they don’t tell the whole story and leave people less experienced believing a lie or at least a semi truth.
In the two examples there is already a problem that is using a global variable and this should be avoided. Worse, at least in these example there is no reason to have this global variable. So if you solve this problem there is no need to extern
. But if you insist on this is not just a matter of saving memory, it’s a question of saying it’s the same variable. If it is the same, you are not putting both statements in the same memory storage location to save memory, you are doing this because it is the same thing, there can be no two.
Today the extern
is used more for functions that are in other compilation unit.
There is almost a book on the subject in response in the OS. The summary there is: if you are not a beast in programming do not use extern
variables, or global variables in general.
Apparently, it lacked more detail on the sample codes I put in. I understand that global variables are used in larger projects, precisely when multiple sources need to access them - and that’s what I meant by codes. My question was whether, in large projects, when multiple sources need to access a variable, there would be some reason to choose between code 1 or code 2. But his mention of the L1 cache made me rethink about memory usage, and the reference of the "book in response" It’s clearing things up a little bit. Grateful.
– HugoB