-1

I am stuck at a program where I have to convert “for-loop”/“do-while loop” to “while loop” without changing the meaning of the program. There may be loops inside loops and so on. The input would be a C language program and output would be a valid C language program.

The solution I got so far is to read a C program from a file and if I detect a for statement, I take the initializer out and replace "for" with "while".

But I am not getting as to how to do it.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
PeakyBlinder
  • 1,059
  • 1
  • 14
  • 35
  • This isn't something that you'd handle at the lexical analysis level, but rather in the parser or as an AST->AST transformation after parsing. – sepp2k Feb 21 '20 at 12:58

1 Answers1

1

As a hint, a for loop consists of an initializer, a condition and an updater

`for (initializationStatement; testExpression; updateStatement)
    {
        // statements inside the body of loop
    }`

you would need something like

initializationStatement;
while( testExpression ) {

    updateStatement;
}
newbie
  • 558
  • 7
  • 12
  • 1
    I feel like OP is asking how to implement this transformation, not what the result should be. – sepp2k Feb 21 '20 at 21:35
  • @sepp2k Yes, I was asking for its implementation. – PeakyBlinder Feb 22 '20 at 06:08
  • How will I implement this in my lex code? What should I write inside this regex %% _mycode_ %% – PeakyBlinder Feb 22 '20 at 06:09
  • @AmberBhanarkar What you should write inside the regular expressions are the lexical rules of the C language, just like in any other C lexer. As I said in my other comment, this transformation is something you'd implement in the parser or afterwards - not in the lexer. – sepp2k Feb 22 '20 at 11:18
  • Sorry , is it this bit your looking for (excuse the pun) it shows more than the For loop but you can rip that bit out https://github.com/TheNilesh/lex-yacc/blob/master/loops.y – newbie Feb 22 '20 at 18:06