Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/Java recursion variable initialize

I wonder why this C++ code is valid and doesn't cause any errors:

extern int B;
int A = B;
int B = A;

int main()
{
    printf("%d\n", B);
    system("pause");
    return 0;
}

First, the variable A will be created in some memory address, then its value will be initialized from variable B, but then variable B goes back to initialize its value from variable A, and so on, ...
So, why is there no infinity loop or any error here?
The program still runs ok, and the value of B is 0

This is valid for Java as well:

class A {
    static final int AA = B.BB;
}

class B {
    static final int BB = A.AA;
}

Any one can explain these questions for me, thanks!

like image 416
phibao37 Avatar asked Mar 10 '23 17:03

phibao37


2 Answers

Since I´m not familiar with c++ I can only explain it to you with the java example.

I think this might explain the issue:

class A {
    static final int AA = B.BB;
}

class B {
    static final int BB = A.AA;
}
  • A.AA gets initialized with value 0

  • A.AA looks for B.BB

  • B.BB gets initialized with value 0

  • B.BB looks for A.AA

  • At this time A.AA already has the value zero (default value of int), so B.BB becomes 0.

  • A.AA becomes 0

like image 130
Tim Schmidt Avatar answered Mar 19 '23 03:03

Tim Schmidt


I am answering this for C++. Although the story might not be all that different for Java

It is not an infinite loop because everything is resolved at compile time, and here is how:

  • The compiler sees that B is declared as extern
  • The linker knows that A has to be set to the value of whatever B is supposed to be when it is declared, so setting the value of A is delayed until much later
  • B is finally declared but since it is not assigned a value, it gets a default value of 0.
  • The linker finally resolves the value of A and can now set it to 0 as well.
  • Compiler compiles your program and the output is 0

See this answer for more details

like image 36
smac89 Avatar answered Mar 19 '23 02:03

smac89