#include <stdio.h>
class C
{
public:
static int i;
static int j;
};
int i = 10;
int C::i = 20;
int C::j = i + 1;
int main ()
{
printf("%d", C::j);
return 0;
}
What is the value of: C::j
I was reading a c++ quiz and came across the following question. I thought that the answer is 11
.
int C::j = i + 1;
Since it is accessing the non static i
which is 10? So, I thought 11
should be the answer?
I compiled and ran this code through visual studio and it prints 21
. Which is confusing to me. Can someone please explain why this is happening? What am I missing?
Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables. A single copy to be shared by all instances of the class. A static variable can be accessed directly by the class name and doesn't need any object.
static initialization does not happen at compile time.
Variable in a Static Block In this case, the variable initialization will be in sequence. For instance, the JVM initially assigns variable z to a default int value of 0. Then, in the static block, it is changed to 30.
Initialization of Instance variables But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables.
[basic.lookup.qual]/3
In a declaration in which the declarator-id is a qualified-id, names used before the qualified-id being declared are looked up in the defining namespace scope; names following the qualified-id are looked up in the scope of the member’s class or namespace.
In
int C::j = i + 1;
the declarator-id, i.e., the name of the entity being declared, is C::j
, which is a qualified-id. Therefore, the i
following it is looked up in the scope of C
, and refers to C::i
.
Less technically, when you define a static data member, the initializer can be thought of as being in the scope of the class, and will find class members before globals.
This is the same rule that ensures that when a member function is defined out-of-line, names after the name of the function will be looked up in class scope and won't require explicit qualification if they refer to class members. It is more unusual seeing this being applied to definitions of static data members, but it is perfectly consistent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With