The question is a stupid one!
This is a stupid question.
Why would any one write a piece of code like this that could easily trick the majority of programmers ( and could trick the compiler just as easy, too). As shown in previous follow ups, most people gets it wrong.
As a member of a software development team, your responsibility is NOT to write a piece of "smart" code that only you can understand correct and that is deemed to be mis-interpreted by other programmers, and even mis-compilered by the compiler, too! If you do so it doesn't show you as smart, it shows you as stupid.
Your responsibility, is to write crystal clear code which leaves absolutely no room for ambiguity what you intend to do and what happens first and what happens next. It needs to be so readable that even a junior programmer can read and understand it correctly. This is how a software team can produce bug free software.
OK, Here is my explaination
To find out why you are getting 10, 5, instead of 8,5, what you need to do is not to read a book, but see exactly what the compiled code look like.
Let me quote your code again here:
class B
{
public:
static int i;
static int j;
};
static int i = 3;
int B::j = i + 5;
int B::i = 5;
Pay attention to the last three lines. If you looked at the compiled code, you will realize that for those three lines, two of them compiles into NOTHING, only the the middle line compiles into something that is executed at run time.
Why? Because that two line has already been resolved by compiler at compiler time. So there is no need to execute anything for that two line. The compiler leaves only the middle line to be executed at run time.
That means, when the program is loaded, even before the very first line of code is executed, the global int i is already 3 and the static class member i is already 5. So when the code execute
int B::j = i + 5;
the result is 10.
Does that explaination make sense?
BTW The i is the class member.
BTW in
int B::j = i + 5;
The i is the class member (B::i), not the global i. When you have name conflict, the compiler will always assume the variable is the one with smallest scope. It first tries to recognize the variable as a local variable, and then as a class member, and then as a variable in current name space, and then a global variable with no name space.