How compiler find for initialized/ uninitialized variable
Mansi Agarwal
Ranch Hand
Joined: Apr 11, 2012
Posts: 53
posted
0
Hi, I just read that- Compiler can detect in very simple conditional cases, that a local variable will be initialized, but will complain in complex cases.
e.g.
Can anyone please explain it how to find whether compiler gives error or not!!
if the condition is compile time constant, then compiler assumes that block executes.
Stuart A. Burkett
Ranch Hand
Joined: May 30, 2012
Posts: 318
posted
0
In your first example either line 6 or 8 will be executed, so there is no path through the code where i would not be initialised.
If you meant to write just
and wondered why that compiled and the second example didn't, it's because true is a compile time constant. The compiler knows it will always be true, whereas in your second example b is a variable and even though it is set to true on the previous line, the compiler doesn't take that into account and so complains.
If you made b a final variable, it would again become a compile time constant and the compiler would be happy again.