I am preparing for a Compilers exam and I found the following two questions in past papers that I don't know how to answer:

1. Array bounds checking requires code to check each array subscript to ensure it
falls within the array's declared range. How could induction variable analysis be
used to avoid repeated bounds checks in "for" loops.

2. Give a short example in Java in which one array address calculation is loop-
invariant and another array address is an induction variable.

I know what an invariant and induction variable means but I don't really know what is expected of me with regards to explaining these two solutions.

I would appreciate it if someone helped me with an explanation.

Thanks!

有帮助吗?

解决方案

The first one is pretty simple - since induction variables go up by fixed amounts per iteration, you can pre-compute the maximum value for any induction variable used as an array subscript and check that it doesn't exceed the array bounds. You'd do this once, before executing the loop, rather than checking the subscript on each iteration.

As for the second, there are plenty of examples (in various languages, including Java) of loop-invariant and induction-variable loops out there - just Google for those terms.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top