In: Computer Science
Explain using the operational semantics the meaning of the for syntax in C :
for (expr1; expr2; expr3) {
. . .
}
(C for) for (expr1; expr2; expr3) ...
evaluate(expr1)
loop: control = evaluate(expr2)
if control == 0 goto out
...
evaluate(expr3)
goto loop
out: ...
for(expr1; expr2;expr3)
In c and many other languages the syntax of for loop is same as above
I will explain all the 3 expressions individually,
expression 1: This is the initialization of the loop it is executed atleast once after that the execution of it depends on condition.
expression 2: This is the condition of the loop it is also executed once and if the condition is true then the block of code inside the for loop executes otherwise the loop is terminated.
expression3: It will be some operation on loop control variable it can be either increment or decrement or any other operation which will continue loop in certain range of values.
Example:
for(i=0;i<10;i++)
here init expression is i = 0;
condition is i<10
expression 3 is increment loop control variable i.
it will get executed 10 times in total
for(i=10;i<20;i=i+2)
here init expression is i = 10;
condition is i<20
expression 3 is increment loop control variable i by 2.
it will get executed 5 times in total