OpenQASM Syntax

OpenQASM is a programming language to create Quantum Programs. Therefore, like any other programming language, OpenQASM has its rules and syntax. OpenQASM is inspired by the QASM or Quantum Assembly language and borrows concepts from C and Assembly language. In this chapter of the OpenQASM 3 tutorial, you will be learning about the basic rules and syntax of OpenQASM programming language.

If you have prior knowledge of OpenQASM 3 Syntax, you can skip this chapter.

OpenQASM Statements

A statement expresses an action that is to be performed. Statements are the most fundamental unit of any program. A program can be thought of a sequence of one or many statements.

In OpenQASM, statements consist of the instruction to be performed and are always followed by a semicolon- ; which marks the end of the statement.

The code below shows a sequence of abstract statements.

statement1;
statement2;
statement3;

The above sequence of statements can also be written as-

statement1; statement2; statement3;

Note– While both the methods of writing multiple statements is correct, the former method is preferred over the latter one.

Example

The code below consists of multiple statements each one containing an instruction to perform.

// First statement
qubit[2] q;

// Second statement
h q[0]

// Third Statement
x q[1]

You will learn in later chapters about what these statements do.

OpenQASM Whitespaces

OpenQASM 3 ignores whitespaces, just like OpenQASM 2. Whitespaces as character that do not consist of any visible marks. Example of white space include spaces, horizontal tab, new line characters, etc.

Example

The following two code sections are the same. This is because OpenQASM ignores whitespaces, which in this case is extra spaces.

qubit[2] q; h q[0];
qubit[2] q[2];               h q[0];

OpenQASM Identifiers

Identifiers are the names given to any user defined variable. There are different types of variables about which you will learn in later chapters of this tutorial.

The rules for identifiers are relaxed in OpenQASM 3 as compared to OpenQASM 2. All identifiers in the OpenQASM 3 programming language must follow the following rules-

  • Unlike OpenQASM 2 where all identifiers must start with a lower-case letter, identifiers in OpenQASM 3 can start with lower-case letters, upper-case letters, underscore, or a range of unicode characters.
  • The name of an identifier cannot be a reserved keyword in OpenQASM 3.

For example, the following are valid identifier names- qcq0q_q_0QCQ0_Q0_q.

Note– The reserved keywords in OpenQASM 3 are different from that of OpenQASM 2. Do keep this in mind when writing OpenQASM 3 code.