int number = 0;
int main() {
printf(" The number is %d\n", number);
return (0);
}
Here number
is a global variable. It has lifetime across application and visibility, scope within the entire file where it was declared, and eventually it can be declared to be included and accessed externally to this file, which is even worse.
This makes the code less readable and makes maintenance difficult. Variables should be declared as close as possible to where it will be needed, should have the smallest possible scope and lifespan to save battery or general memory and to prevent something from being done with it inadvertently.
The variable will be in a static area of memory and concurrent access to it will be problematic.
int main() {
int number = 0;
printf(" The number is %d\n", number);
return (0);
}
I put in the Github for future reference.
Here number
is a local variable that will only exist in pile for a short time (during function execution) and cannot be accessed outside function.
It is easier to track your state because it cannot be modified at other points in the application. Imagine how hard it is to debug something that might have its status changed at various points.
In fact the variables should have the scope even smaller, whenever possible. It is common to see in C programmers declaring all variables at the beginning of the function. This was even necessary at the beginning and has a lot of example like this. But the right thing to do is to declare it in the smallest possible scope. If you have a code block and the variable will only be inside it, state inside, do not leave the variable in the scope of the whole function. In fact, even if I can’t use a smaller scope, it is only possible to declare the variable when it is used, the code becomes more readable. It’s just no more than avoiding an unnecessary variable for the algorithm.
I see beginner programmers creating global variable so they don’t have to pass local variables like arguments for other functions. Essentially, it’s always a mistake to do this. In well-written applications we can say that we never need global variables (although it’s never an exaggeration).
Of course, in simple examples like this it doesn’t seem to make a difference, and in this one it doesn’t really make a difference, but get used to doing it in the best way, in more complex applications it is very important to have code organization and decrease the surface where problems can occur.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.
– Maniero