-2

Today, I'm done with my Compiler Construction finals paper at university. The finals paper included a question that asked me to convert a for loop into 3-address code. The function it asked me to convert was:

for(i=1;i<=10;i++) x=y+z

So, I did loop unrolling and converted the given statements to the equivalent expression:

x=(y+z)^10

Then, I made 3-address code of the converted code:

1

Please let me know if it is correct.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • Was this for a specific language or is this pseudocode? – Jonathan Joshua Jun 27 '22 at 15:53
  • 5
    There's no image, but executing `x=y+z` ten times is not the same thing as setting `x` to `(y+z)^10`, and doing something like that may not be the intention of the question (partly the fault of the question) – harold Jun 27 '22 at 15:54
  • It was just a question in c language and I just needed to make 3-Address code of it. And I found it hard to solve so I just done some loop optimization and convert it in another form. – Sania Bilal Jun 27 '22 at 15:59
  • Your loop optimization was incorrect. Hint: what's the value of `x` after `x = y+z` executes in the final iteration of the loop? Does it depend on any previous value of `x`? Also, the `^` operator in C is XOR, not exponentiation, in case you thought something was getting multiplied 10 times instead of assigning the same value repeatedly. – Peter Cordes Jun 28 '22 at 03:18
  • @Lambdaus - your edit missed the image the querent added to their post a couple minutes before your suggested edit. It also didn't fix the lack of code formatting for the code. It was still somewhat of an improvement so I decided to "improve and edit" instead of reject, but in future prefer leaving a little vertical space for paragraphs, and use code formatting not bold for code. Thanks for helping to edit stuff on stack overflow :) – Peter Cordes Jun 28 '22 at 03:21

1 Answers1

0

Your converted code is wrong.

In the original, x is not dependent on past versions of x making the for loop dead code and loop unrolling useless as @Peter Cordes stated. If your looking for the correct answer, the correct non-optimized answer would be:

(0) i=1
(1) if(i > 10) goto 5
(2) x=y+z
(3) i=i+1 
(4) goto 1
(5) end

While, the correct optimized answer would be:

(0) x=y+z
(1) end
Lambdaus
  • 22
  • 4