Kal Kal - 2 months ago 7
C Question

How to exit infinite for(;TRUE;) in C?

I am running a simulation which uses an infinite for loop. TRUE is defined as 1. Inside the loop, each call containing "state" is a function that returns void.

/* main sim loop */
for (i = 0, num_insn = 0; TRUE; i++) {
writeback(state, &num_insn);
execute(state);
if (!(state->fetch_lock)) {
decode(state);
fetch(state);
}
}


I would like to eventually exit the loop from inside of an "if" statement in the writeback function. How is this done? I tried to use "break" but I get an error when I compile.

EDIT: Inside the writeback function

if ((state->fetch_lock == TRUE)&&(fu_int__done == TRUE)&&(fu_fp_add_done ==TRUE)&&(fu_fp_mult_done == TRUE)&&(fu_fp_div_done == TRUE)) {
break;
}


which gives compile error "error: break statement not within loop or switch"

Answer

The writehack function can be called from anywhere.

Change it to

   bool writeBack(...) {
    ...
    return true; // Break is require if in a loop
    return false; // Otherwise;

Then

for (i = 0, num_insn = 0; TRUE; i++) {
  if (writeback(state, &num_insn) ) {break; }
  execute(state);
  if (!(state->fetch_lock)) {
    decode(state);
    fetch(state);
  }
}