Search code examples
rloopslabelgoto

What would be an r equivalent of goto statements (from e.g. c++) here?


I realised that r does not have goto statements, and I'm currently translating some C++ code that had them. In the follow code the goto loop is supposed to make the function go back to "loop:" and start running the code from there. How could you achieve a similar result in r?

Solve <- function() 
{
  statements
  loop:
    iter_time <- iter_time + 1
  if (conditions) {
    statements
  } else if (conditions) {
    statements
    if(conditions) {
      statements
      if (conditions) {
        statements
      } else {
        statements
      }
    } else {
      goto loop
    }
  }
}

Solution

  • You can use next to go back to the start of the loop. For example:

    for (i in 1:5) {
            if (i == 2) {
                    print(paste0(i, " is a cool number!"))
            }
            else if (i == 3) {
                    print(paste0(i, " is an awesome number!"))
            }
            else {
                    next
            }
    }