Take the 2-minute tour ×

I got this problem wrong on my homework, and I can't figure out why:

procedure Main is
    X: Integer;
    procedure Sub1 is
       X: Integer;
    begin -- of Sub1
    end; -- of Sub1
    procedure Sub2 is
       X: Integer;
    begin -- of Sub2
    end; -- of Sub2
begin -- of Main
end; -- of Main

The Question is: Assume the following Ada program was compiled and execute using static-scoping rules. What value of X is printed in procedure of Sub1? What if it was under dyncamic scoping rules?

I got 12 and 5 respectively, but this was marked incorrect. Why?

share|improve this question
add comment

closed as too localized by Erick Robertson, Deanna, Jack, Kris, BNL Oct 3 '12 at 13:18


3 Answers

Step through the program more carefully. Where is the value coming from in Sub1?

share|improve this answer
Is it the new initialized integer? So what would X be if it's not declared with a value? 0? –  kylex Mar 6 '09 at 23:32
I don't recall if Ada initializes variables for you or not. I'd have to go dig up my text book from the basement somewhere. I suspect yours is easier to get to ;-) –  Ryan Graham Mar 6 '09 at 23:35
add comment

Ada uses static (lexical) scoping rules, but even if it didn't it's hard to see what the Put(X) in Sub1 can be referring to other than the uninitialised X 2 lines above it. The value printed will likely depend on the OS, the compiler flags used and perhaps even the time of day.

After correcting the code, the answer (using various GNATs on Mac OS X) was 0 using -O2 for all of them, but without optimisation GCC 4.3.3 gets 42291, GNAT GPL 2009 (which is a 64-bit compiler) gets 16777216, and a recompilation of GNAT GPL 2009 for 32-bits gets 1.

share|improve this answer
add comment

Hint: under static scoping it's uninitialized. Can you figure out why?

share|improve this answer
add comment
