static variablen?
-
was ist der unterschied zwischen normalen und staic variablen?
-
Normale Variablen gelten nur in dem Block (Scope?) in dem sie deklariert wurden, danach verschwinden sie:
while ( tolle_bedingung ) { int x = 0; //hier lebt x for (int i = 0; i != 67; i++) { ... //Hier lebt i ... } //hier verschwindet i //hier lebt x immer noch } //hier verschwindet x
Wenn du eine Variable als static in einer Funktion deklarierst, bleibt ihr Wert auch nach dem Verlassen dieser Funktion erhalten. Man kann die Variable aber glaube ich nicht von aussen verändern, wie das bei globalen Variablen geht.
Beispiel (ungestestet, sorry) für eine "Zähl-Funktion", die bei jedem Aufruf eine Zahl ausgibt, die um eins höher ist als die Zahl beim vorherigem Aufruf:
void counter() { static zahl = 0; +++zahl; cout << zahl << " mal aufgerufen\n"; }
-
genau, man hat von außerhalb keinen zugriff. und was noch ein wichtiger unterschied ist: static variablen werden im gegensatz zu auto variablen immer mit 0 initialisiert (wenn das möglich ist)
-
Hi,
was man vielleicht noch erwaehnen kann, wenn du in einer UE eine globale Variable als static
deklarierst, dann ist diese Variable _nur_ in dieser UE sichtbar.mfg
v R
-
dann muss man aber dazu sagen, dass das deprecated ist und du lieber einen unnamed namespace verwenden solltest
-
davie schrieb:
dann muss man aber dazu sagen, dass das deprecated ist und du lieber einen unnamed namespace verwenden solltestJa, da stimm ich dir voll zu, wollte es nur nicht unerwaehnt lassen und bin auch darauf
gekommen, da im alten Code unseres Produktes diese Technik sehr konsequent durchgehalten
wurdemfg
v R
-
davie schrieb:
dann muss man aber dazu sagen, dass das deprecated ist und du lieber einen unnamed namespace verwenden solltestIst das nicht egal?
Was static sonst noch bedeuten kann, steht auch in der FAQ.
-
egal == dieses mal klappt's noch?
-
Nee, war als Frage gemeint, ob ich nun tatsächlich statt static einen namespace nehmen soll.
-
naja, später einmal wird eben nur noch der unbenannte namespace erlaubt sein...
also ist der dem static vorzuziehen, wenn du zumindest das zukunftssicher machen willst
-
Nee, war als Frage gemeint, ob ich nun tatsächlich statt static einen namespace nehmen soll.
unnamed namespaces haben die Vorteil, dass ihre Elemente zwar wie static-Variablen nur innerhalb der UE ansprechbar sind, dennoch aber external linkage haben und damit als Templateparameter verwendet werden können.
-
Ahja, Danke.