2.5. Control flow

There are standard constructions for defining the control flow of the program.

The control flow of the computations is like in other imperative languages, but the instantiation of components may not follow the sequential structure of the code as if they may depend on some input signal. The component instantiation will not be triggered until all input signals have a concrete value assigned.

Conditional statement: if-then-else

if ( boolean_condition ) block_of_code else block_of_code

The else part is optional. If not included it means "else do nothing".

if (x >= 0) {
x = y + 1;
y += 1;
} else {
x = c.b;
}

Loop statement: for

for ( initialization_code ; boolean_condition ; step_code ) block_of_code

If the initialization_code includes a var declaration, then its scope is reduced to the for statement and hence, using it later on (without defining it again) will produce a compilation error.

template Bits2Num(n) {
signal input in[n];
signal output out;
var lc1=0;
var e2 = 1;
for (var i = 0; i<n; i++) {
lc1 += in[i] * e2;
e2 = e2 + e2;
}
lc1 ==> out;
}

Loop statement: while

while ( boolean_condition ) block_of_code

It executes the block of code while the condition holds. The condition is checked every time before executing the block of code.

template Bits2Num(n) {
signal input in[n];
signal output out;
var lc1=0;
var e2 = 1;
var i = 0;
while(i<n){
lc1 += in[i] * e2;
e2 = e2 + e2;
i = i+1;
}
lc1 ==> out;
}

Loop statement: do-while

do block_of_code while ( boolean_condition )

It executes the block of code until the condition fails. The condition is checked every time after executing the block of code.

template Bits2Num(n) {
signal input in[n];
signal output out;
var lc1=0;
var e2 = 1;
var i = 0;
do{
lc1 += in[i] * e2;
e2 = e2 + e2;
i = i+1;
}while(i<n)
lc1 ==> out;
}

When constraints are generated in any block inside an if-then-else or loop statement, the condition must not be unknown. This is because the constraint generation must be unique and cannot depend on unknown input signals. In case the expression in the condition is unknown and some constraint is generated, the compiler will generate an error message.

Another compilation error is generated when the content of a var depends on some unknown condition: that is, when the var takes its value inside an if-then-else or loop statement with unknown condition. Then, the content of the variable is a non quadratic expression and, as such, cannot be used in the generation of a constraint.