Are the following declarations correct?
Outside any function:
int a; //external by default
extern int a; //explicitly extern
static int a; //explicity static
const int a; //static by default
static const int a; //explicitly static
extern const int a; //explicitly extern
Inside a function:
int a; //auto by default
static in a; //explicity static
const int a; //static by default
static const int a; //explicitly static
Close.
Anything at global scope (ie: outside a function) is static by default.
eg:
However, if you explicitly declare something at the global scope as static, not only is it static, but it is only visible inside that file. Other files can’t see it.
Also, nothing is “extern” by default. You typically use extern to access global variables from other files, provided they weren’t explicitly declared static as in the example above.
const only implies that the data cannot change, regardless of it’s scope. It does not imply extern, or static. Something can be “extern const” or “extern”, but “extern static” doesn’t really make sense.
As a final example, this code will build on most compilers, but it has a problem: myVar is always declared “extern”, even in the file that technically creates it. Bad practice:
Finally, you might want to cover this post on the various levels of scope if you are not already familiar with them. It will likely be helpful and informative to you. Good luck!
Terminology definition – Scope in C application
The person who answered this question of mine on scope did a good job, in my opinion.
Also, if you declare something static within a function, the value remains between function calls.
eg:
Output:
Note that the use of a static variable within a function has a specific and limited number of cases where they are useful, and generally aren’t a good idea for most projects.