What is default storage class for global variables?

余生长醉 提交于 2019-11-28 07:35:30

The default storage duration is static, but default linkage is external. You're not the only one to find it a bit confusing. The C Book (always a good reference) says:

"You'll probably find the interactions between these various elements to be both complex and confusing: that's because they are!"

The section with that quote, Declarations, Definitions and Accessibility, has a helpful table (8.1). The last row describes the case you're interested in. As it notes, data objects with no storage class specifier have external linkage and static duration.

There's no "default storage class" for what is commonly known as "global" variables. When a variable is defined in namespace scope it always has static storage duration. There's no way to change that, which is why the idea of something "default" is not applicable here. (And storage duration is what it is correctly called.)

When you apply the keyword static to a variable defined in namespace scope it does not affect its storage duration - it was static already and it remains static - but it affects it linkage. The keyword static changes the linkage of such variable from external (default) to internal. Linkage is a separate concept, virtually unrelated to storage duration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!