ModelSim VHDL – Nested ‘for’ loops behaviour

loopmodelsimvhdl

I've now been a couple years working with VHDL in college and I've been using ModelSim to simulate my designs. Today, however, I noticed something I couldn't understand about for loops, so I thought I'd ask it here 🙂

When using two nested for loops with the same variable, such us:

for i in 0 to 9 loop
  for i in 0 to 7 loop
    mySignalVector(i)<=myOtherSignal;
  end loop
report integer'image(i);
end loop

This works perfectly, repeating the "father" loop 10 times (and therefore preserving the i value, so the reported messages are values from 0 to 10). I don't understand this, as it should replace the value for the ones in the nested for loop.

So the question is, how do for loops work in VHDL Testbench to produce this behaviour?

Thanks!

Best Answer

Many languages have scoping rules that treat variables defined in outer blocks as read-only in inner blocks. In the inner 'for', the attempt to write to a variable 'i' creates a new one that's in scope in the inner 'for' only. With a namespace per block, the compiler is not confused between outer.i and inner.i.

Even if it does work, it's certainly confusing for the programmer, and so should not be used. Is that report statement printing the final value from the inner loop, or the current value from the outer loop?

There's an annual competition to obfuscate C code, but just because you can write a program that works and looks wrong doesn't mean you should.

You will forget what you wrote in a few weeks' time, and anybody else seeing it will think 'wtf?'. If you write the hardware for a missile relying on this construct, and then the language gets updated at a later date to eliminate 'confusing' behaviour, then you'll be in trouble if it ever gets recompiled.