int number = 0;
int main() {
printf(" The number is %d\n", number);
return (0);
}
Here number
is a global variable. It has lifetime across the application and visibility, scope within the entire file where it was declared, 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 more difficult. Variables should be declared as close as possible to where it will be needed, should have the smallest scope and lifetime possible to save stack or general memory, and to prevent something from being inadvertently done with it.
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);
}
Here number
is a local variable that will only exist in the stack for a short time (during the execution of the function) and can not be accessed outside the function.
It's easier to track its status because it can not be modified elsewhere in the application. Imagine how difficult it is to debug something that can have its state altered at various points.
In fact, the variables should be scoped up 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 many such examples. But the correct thing is to declare in the smallest possible scope. If you have a block of code and the variable will only be inside it, declare in there, do not leave the variable in scope of the whole function. Actually even though I can not use a smaller scope it is useful to declare the variable only when it is used even, the code becomes more readable. All that is left is to avoid an unnecessary variable for the algorithm.
I see beginner programmers creating a global variable so that they do not have to pass local variables like arguments to other functions. Essentially it is always a mistake to do this. In well-written applications we can say that we never need global variables (although it is never an exaggeration).
Of course, in simple examples, it seems that it does not make a difference, and in this case it does not, but it is customary to do it in the best way, in more complex applications it is very important to organize the code and to reduce the surface where problems can occur. / p>