views:

187

answers:

3

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
        Put(X);
        end; - of Sub1
    procedure Sub2 is
        X: Integer;
        begin - of Sub2
        X:=5;
        Sub1
        end; - of Sub2
    begin -of Main
    X:=12;
    Sub2
    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?

+2  A: 

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

Ryan Graham
Is it the new initialized integer? So what would X be if it's not declared with a value? 0?
kylex
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
+1  A: 

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

MarkusQ
+1  A: 

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.

Simon Wright