-1

While studying for my exam I saw a question which is as shown below can someone please explain to me that does the ';' means at the end of the for loop and can I also put it in a while loop? And what is the difference between the Compile-time error and the Compilation error?

#include <stdio.h>

int main(){
    int value;
  for ( value = 1; value <= 15; value+=3);{
      printf("%d", value);
  }
  
  
return 0;
}


GamerToonz
  • 51
  • 4
  • Look up this question: https://stackoverflow.com/questions/10293711/for-loops-and-stopping-conditions – Matteo Galletta Jan 21 '21 at 11:36
  • Does this answer your question? [For Loops and stopping conditions](https://stackoverflow.com/questions/10293711/for-loops-and-stopping-conditions) Edit: Better dup: [Effect of semicolon after 'for' loop](https://stackoverflow.com/q/13421395/364696) – ShadowRanger Jan 21 '21 at 11:38
  • _Compile-time error and the Compilation error_ both are same !!!! – IrAM Jan 21 '21 at 11:41

2 Answers2

1

This is probably a mistake; it is syntactically correct, but actually would be read by the compiler like this:

for (value = 1; value <= 15; value+=3);

// Unrelated block!
{
   printf("%d", value);
}

This means that the loop will execute, then run four more times, but not actually do anything, then the block will execute once.

Where the loop and the block following it are completely separate and unrelated.

Ben Wainwright
  • 4,224
  • 1
  • 18
  • 36
0

The semicolon ; terminates the definition of the loop body. In this case there are no statements in the body of the loop, hence the only affect of the loop is to modify the value of the counter variable, value.

The statement following the semicolon has it's own scope thanks to the curly braces, but it has no real affect in this case.

The printed result will be the value of value after the (empty) loop has executed, i.e. 16.

You could not do the same with a while loop because the variable would need to be incremented within the body of the loop and the value tested at each iteration to decide whether to continue looping.

Of course, you could avoid any loop by initialising value to 16.

mhawke
  • 84,695
  • 9
  • 117
  • 138