Quantcast
Channel: Recent posts
Viewing all articles
Browse latest Browse all 415

Nested blocks mess up variables

$
0
0

According to the manual, a BLOCK construct is itself a scoping unit. At the same time, BLOCKs can be named, and the names must be unique within their scoping unit. This means that by putting blocks inside each other, they can have the same name, since they form new scoping unit.
Variables inside a block are supposed to hide variables of the same name outside of the block. Hence, the following code should, and does, print 1, 2:

block
   integer :: a = 1

   block
      integer :: a = 2

      print *, a
   end block
   print *, a
end block

This is fine. Now I give a name to the blocks, and I choose the same name. For this, a third block is required which allows me to use the name again.

aName: block
   integer :: a = 1

   block
      aName: block
         integer :: a = 2

         print *, a
      end block aName
   end block
   print *, a
end block aName

This time, the output is 1, 1, and by looking at the assembler output, the compiler indeed assigns the very same position in memory to the two variables a. If, instead of using the initialization statement, I directly set the values to 1 and 2 after declaration, the output is 2, 2. The problem is not caused by the third block, but by the double names.

Compiler: Visual Fortran Compiler 17.0.2.187


Viewing all articles
Browse latest Browse all 415

Trending Articles