What does the use of 'static' do in C++?

Started by
6 comments, last by Gamer Gamester 21 years, 1 month ago
Hello, I''m curious about the use of the prefix ''static'' for variables and functions in C++. I understand it''s use in classes: having one variable for every instance of the class. But in a large amount of sample code I''ve studied, I notice people often will declare functions and variables as ''static'' even though they are not in any class. What does this do? It doesn''t seem to have any effect on the final program as far as I can tell. I imagine it has something to do with how the variable/function is loaded into memory, but I''m very curious and want to know the details. Thanks, Beau
Advertisement
The choice of the 'static' keyword in C/C++ was very unfortunate. It designates several different processes and purposes, depending on the scope and context.

Outside of a class or function (ie. applied to global data), it is a scoping mechanism. It means, that the variable will only be visible to the current compilation unit (source file). This use is deprecated in C++, and should be avoided. Putting the variables into an unnamed namespace has the same effect.

Using the static keyword on a variable declared in a function is a much more important feature. It states, that the local variable/object should be allocated on the heap, instead of the stack. That means, that the object is constructed (or initialized) the first time the function is called. It then stays in memory until the program ends, ie. it will continue to exist, even if the current function is exited. On the next function call, the variable will not be constructed/initialized again (it was never deleted), but will keep the value it had from the previous function run instead.

Local static objects can be quite useful, and can be used to implement singletons, for example.


[edited by - Yann L on March 6, 2003 11:35:16 PM]
One last meaning of static: Applying "static" to a class member variable means that only one copy of that variable exists for all objects created. Applying "static" to a class member function means that that function is not called on an object of that class, and does not recieve a "this" pointer.

But... but that''s what HITLER would say!!
Since he said that he knew about the use in a class, I left that one out.
Incidentally, the effects of static and of the unnamed namespace aren''t quite the same : static forces internal linkage°, while the unnamed namespace usually uses mangling to prevent linkage, but doesn''t actually affect the linkage status of a symbol.

In other words, you cannot have an extern static (it''s still just static), but you can have an extern within the unnamed namespace. For other compilations units, it doesn''t matter, but there is at least one case I am aware of where it does : if you want to use a pointer as a non-type template parameter, the object it points to must have external linkage (so that all templates using it as a parameter really resolve to the same type, otherwise it would be a violation of the one-definition rule).

So :


  #include <iostream>using namespace std;template<const char* str> struct foo{  static void print() { std::cout << str << std::endl; }};static const char s1[] = "foo";extern static const char s2[] = "foo";namespace{  extern const char s3[] = "foo";}int main(){  foo<s1>::print();  foo<s2>::print();  foo<s3>::print();}  


gcc correctly rejects s1 and s2 as an invalid template parameter, while s3, actually being extern, is accepted.

° for those who don''t know, ''linkage'' relates to whether a symbol can be referred to from another compilation unit. i.e. whether the linker is aware of it.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
quote:Original post by Yann L
Using the static keyword on a variable declared in a function is a much more important feature. It states, that the local variable/object should be allocated on the heap, instead of the stack.


Um, I think the standard leaves the exact location up to the implementation, but any sane compiler will place them in a data segment (i.e. just like a global variable).



- Magmai Kai Holmlor

"Oh, like you''ve never written buggy code" - Lee

[Look for information | GDNet Start Here | GDNet Search Tool | GDNet FAQ | MSDN RTF[L] | SGI STL Docs | STFW | Asking Smart Questions ]

[Free C++ Libraries | Boost | ACE | Loki | MTL | Blitz++ | wxWindows| Spirit(xBNF)]
[Free C Libraries | zlib ]

- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
quote:Original post by Fruny
Incidentally, the effects of static and of the unnamed namespace aren''t quite the same : static forces internal linkage°, while the unnamed namespace usually uses mangling to prevent linkage, but doesn''t actually affect the linkage status of a symbol.

Yes, of course you are right. But I think one can safely take an unnamed namespace as an adequate replacement for a global static, assuming the typical purpose of local scoping. The namespace will achieve that effect in a different way than the static, but the net result is the same (the symbol will be local to the compilation unit).

The opposite (replacing an unnamed namespace by a static) doesn''t always work, though.
I fully agree. That''s what it has been designed to do

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement