2.7. Scope - JulTob/Ada GitHub Wiki

Variable Scoping and Shadowing in Ada

Ada allows for variables with the same name to exist in different scopes. This is called shadowing, where a variable in a deeper (inner) scope temporarily hides a variable of the same name in an outer scope.

WITH Text_IO; USE Text_IO;
WITH Ada.Integer_Text_IO; USE Ada.Integer_Text_IO;

PROCEDURE Scope_Demo IS
   Var : Integer := 5;  -- Outer scope variable

   PROCEDURE Inner IS
      Var : Integer := -5;  -- Shadows outer scope Var
      BEGIN
         Put("Inside Inner, Var is: ");
         Put(Var, 2); New_Line;  -- Prints -5
         END Inner;

   BEGIN
      Put("In Outer scope, Var is: ");
      Put(Var, 2); New_Line;  -- Prints 5

      Inner;  -- Call the inner procedure

      -- A new scope that declares another Var, shadowing the outer Var
      DECLARE
         Var : Integer := 10;
         BEGIN
            Put("In new inner scope, Var is: ");
            Put(Var, 2); New_Line;  -- Prints 10
            Put("Outer scope Var is: ");
            Put(Scope_Demo.Var, 2); New_Line;  -- Prints 5 (outer scope Var)
            END;

      Put("Back in Outer scope, Var is: ");
      Put(Var, 2); New_Line;  -- Prints 5
      END Scope_Demo;
  1. Outer Scope: The variable Var is initially declared in the outermost procedure Scope_Demo with a value of 5.
  2. Inner Procedure: Inside the procedure Inner, another Var is declared with a value of -5. This Var shadows the outer Var. When you call Inner, it prints the inner Var (which is -5).
  3. Nested Scope (DECLARE): In the nested DECLARE block, another Var is declared with a value of 10. Inside this block, the inner Var shadows the outer one again, but the outer Var can still be accessed using the full path Scope_Demo.Var.
  4. After Nested Scope: Once the DECLARE block ends, the Var declared in it is discarded, and the original Var from the outer scope is accessible again.