static Static storage duration and internal linkage

static Static storage duration and internal linkage

static gives locals static storage, initialized once. File-scope names get internal linkage; block static lacks linkage, adding no const or thread privacy.

CategoryStorage-class specifiers
KindKeyword / Statement
C standardC89 / C90

📝 Syntax

static int counter = 0;  /* Inside a function */

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

first = 1, second = 2
ℹ️ Info The example saves both return values before printing, avoiding evaluation-order issues within one printf call. The local count retains its value between calls.

📚 Related Tutorials

❓ FAQ

QHow many times is a local static variable initialized?
AAn object with static storage duration is initialized once during program startup and is not reinitialized on later function entries. Without an explicit initializer it is zero-initialized; its initializer must meet the rules for static objects.
QDo file-scope static and function-local static mean the same thing?
ANo. File-scope static primarily gives a name internal linkage, while function-local static extends storage duration until program termination. A block-scope static object itself still has no linkage.
QIs a static counter safe in a multithreaded program?
ANo. A local static is still shared by all threads. Concurrent non-atomic increments can cause a data race, so use atomic operations or mutual exclusion as appropriate.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏