{"id":882,"date":"2010-06-12T23:06:03","date_gmt":"2010-06-13T05:06:03","guid":{"rendered":"http:\/\/thesmithfam.org\/blog\/?p=882"},"modified":"2019-08-12T07:15:31","modified_gmt":"2019-08-12T13:15:31","slug":"the-many-meanings-of-the-c-static-keyword","status":"publish","type":"post","link":"https:\/\/thesmithfam.org\/blog\/2010\/06\/12\/the-many-meanings-of-the-c-static-keyword\/","title":{"rendered":"The Many Meanings of the C++ &#8220;Static&#8221; Keyword"},"content":{"rendered":"<p>In C++, the <tt>static<\/tt> keyword has a lot of meanings. Let&#8217;s go over all of them:<\/p>\n<p><b>Meaning 1: Private Linkage<\/b><\/p>\n<p>This one comes from C, and it lets you mark a variable as &#8220;file private&#8221;.<\/p>\n<p>Example:<\/p>\n<pre>\r\nstatic int i = 42;\r\nvoid doSomething()\r\n{\r\n    cout &lt;&lt; i;\r\n}\r\n<\/pre>\n<p>In this example, <b>static<\/b> tells the compiler to not make the variable <b>i<\/b> available from other source files. If another file tries to use <b>i<\/b>, perhaps using the <tt>extern<\/tt> keyword, it would generate a linker error (unresolved external symbol). The same concept applies to functions whose access you want to limit to the current file.<\/p>\n<p><b>Uses:<\/b><\/p>\n<p>This is very handy for creating &#8220;file private&#8221; variables and functions. I recommend using static for any file-only functions. This way, you can name them whatever you like without risking a naming collision in the global namespace.<\/p>\n<p><b>Gotchas:<\/b><\/p>\n<p>Unfortunately, you can&#8217;t declare a class as static. Also, the language makes no guarantee about the order in which static variables are initialized. In my experience, static variables in the same file are initialized in a &#8220;sane&#8221; order, so you can do things like this:<\/p>\n<pre>\r\nstatic int i = 42;\r\nstatic int j = i + 1;\r\n<\/pre>\n<p><b>Meaning 2: Function Call Spanning<\/b><\/p>\n<p>This one also comes from C, and it lets you give a function-local variable a long lifespan. Here&#8217;s an example:<\/p>\n<p>Example:<\/p>\n<pre>\r\nvoid foo()\r\n{\r\n    static int callCount = 0;\r\n    callCount++;\r\n    cout &lt;&lt; \"foo has been called \" &lt;&lt; callCount &lt;&lt; \" times\" &lt;&lt; endl;\r\n}\r\n<\/pre>\n<p><b>Uses:<\/b><\/p>\n<p>it&#8217;s a great way to keep track of how many times a function has been called, so it works well for generating unique ID numbers (watch out for thread-safety!). It&#8217;s also useful to keep track of whether a function is being called for the first time ever, like this:<\/p>\n<pre>\r\nvoid foo()\r\n{\r\n    static bool firstTime = true;\r\n    if(firstTime)\r\n    {\r\n        \/\/ Do something special here\r\n        firstTime = false;\r\n    }\r\n}\r\n<\/pre>\n<p><b>Gotchas:<\/b><\/p>\n<p>Static function-local variables are initialized the <b>first time<\/b> the function is called, not before. Using these kinds of variables can often make your code not thread safe and not re-entrant, so take care before using them. You can put static variables within scope blocks (like inside an <b>if<\/b> or <b>for<\/b> statement). I&#8217;m not totally sure what the implications are, and frankly I&#8217;ve never felt the need to limit the scope of a variable so aggressively.<\/p>\n<p><b>Meaning 3: Per-Class Data<\/b><\/p>\n<p>When you declare a class member as static, it now belongs to the class at large, and not a particular instance.<\/p>\n<p>Example:<\/p>\n<pre>\r\n\/\/ In the .h file:\r\nclass MyClass\r\n{\r\n    public:\r\n        static int FavoriteNumber;\r\n        static void foo();\r\n};\r\n\r\n\/\/ In the .cpp file (to initialize the static variable):\r\n\r\nint MyClass::FavoriteNumber = 42;\r\n\r\nvoid MyClass::foo()\r\n{\r\n    \/\/ can't access member variables here!\r\n}\r\n<\/pre>\n<p><b>Uses:<\/b><\/p>\n<p>It&#8217;s very common to store class-level constants this way. You can declare class functions as static as well, so they would be callable from anyone who has access to your class, even if they don&#8217;t have an instance. This is handy for helper functions. I generally like to make class functions static if they don&#8217;t need to operate on any instance data, typically for private helper functions.<\/p>\n<p><b>Gotchas:<\/b><\/p>\n<p>Static members are initialized very early in your program&#8217;s execution, before <b>main()<\/b> is even called actually. You also have <a href=\"http:\/\/www.parashift.com\/c++-faq-lite\/ctors.html#faq-10.12\">no guarantee about the order<\/a> in which they are initialized between classes in different files. Be careful not to initialize one static class variable from another (possibly not-yet-initialized) static class variable. Also, you can&#8217;t access instance data from <b>this<\/b> within a static class function (unless someone passes you a <b>this<\/b> pointer). Lastly, you have to initialize your static class variables in your implementation (.cpp) file. Otherwise, the compiler doesn&#8217;t know how to allocate them (see the example above).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In C++, the static keyword has a lot of meanings. Let&#8217;s go over all of them: Meaning 1: Private Linkage This one comes from C, and it lets you mark a variable as &#8220;file private&#8221;. Example: static int i = 42; void doSomething() { cout &lt;&lt; i; } In this example, static tells the compiler [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-882","post","type-post","status-publish","format-standard","hentry","category-code-and-cruft"],"_links":{"self":[{"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/posts\/882","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/comments?post=882"}],"version-history":[{"count":12,"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/posts\/882\/revisions"}],"predecessor-version":[{"id":1515,"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/posts\/882\/revisions\/1515"}],"wp:attachment":[{"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/media?parent=882"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/categories?post=882"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thesmithfam.org\/blog\/wp-json\/wp\/v2\/tags?post=882"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}