bogALT bogALT - 1 month ago 12
C++ Question

Static variables in C++ and Java

I have a question:
lets say we have this function: (in C++)

int& f(){static int x = 0; return x;} // OK


and

int& h(){int x=0; return x;} // ERROR


Why
h
gives an error? Is it because of the keyword
static
? I found
static
keyword lets my
x
variable live after my function is terminated. So I still cann acces at that memory location from the outside (another function or main? right?) Instead int
x =0
is lost after
h
terminates. Right? I'm not sure i really got it!

And What about Java? I red I cannot delcare
static
variables in methods but only in Classes.

Thank you.

Answer

In C++, static is one of the most overloaded keywords of the language. The meaning you're using here is this:

A variable which is defined inside a function with the static specifier has static storage duration - it occupies the same space for the entire runtime of the program, and keeps its value between different calls to the function. So you can safely return a reference to it, as the variable is always there to back the reference.

A normal (non-static) function-local variable is destroyed when the function call returns, and so the reference becomes dangling - it doesn't refer to anything valid. Using it results in Undefined Behaviour.

Java simply doesn't have function-scope static variables (it doesn't have that meaning of the keyword static). That's why you can't declare it there.

Both C++ and Java have the "class-scope" meaning of the static keyword. When a member of a class is declared with the static keyword, it means the member is not bound to any instance of the class, but is just a global variable whose identifier lives in the class's scope.

Comments