OpenQASM if Statement

The if statement is a fundamental decision making statement in Classical Computing and is present in every major programming language. OpenQASM also provides the if statement. In this chapter of the OpenQASM tutorial, you will be learning about the if statement and how you use it in OpenQASM.

The if Statement

The if statement in Classical Computing is a decision making statement that executes some Classical Computation based on a condition. If the condition evaluates to true, then the computation is executed, else it is not.

Similarly in OpenQASM, the if statement conditionally executes a Quantum Operation based on the value of a Classical Register. The Quantum Operation is execute iff(if and only if) the integer represented by the Classical Register(with the zero index bit in the register being the least significant) is equal to a particular integer value.

Only Quantum Operations, i.e built-in gates, gate (and opaque) subroutines, preparation, and measurement, can be used with the if statement.

The following syntax is used for using the if statement to execute a Quantum Operation conditionally in the OpenQASM programming language-

if(c_reg==int) <Quantum Operation>

Where c_reg is a Classical Register, int is the integer to which the integer represented by c_reg is being compared, and <Quantum Operation> is any valid Quantum Operation.

Note– Like all other programming languages, the == sign in OpenQASM also checks equality.

Example

Below is an example of using the integer represented by Classical Register c_reg to check if the condition following the if statement- the CX Operation with controlling Qubit q_reg[0] and controlled Qubit q_reg[1] will be executed. The Quantum Operation will be executed only if the integer represented by Classical Register c_reg is equal to 4, i.e- 100(binary of 4).

if(c_reg==4) CX q_reg[0], q_reg[1];

Example

Below is an example in which the integer represented by Classical Register c_reg should evaluate to 1(also 1 in binary) for the U Gate with given parameters(the H Gate) to be applied to the first Qubit(at zero index) of the q_reg Quantum Register.

if(c_reg==1) U(pi/2, 0, pi) q_reg[0];