## 5.9 Compound variable declaration and definition

Stan allows assignable variables to be declared and defined in a single statement. Assignable variables are

• local variables, and
• variables declared in the transformed data, transformed parameters, or generated quantities blocks.

For example, the statement

int N = 5;

declares the variable N to be an integer scalar type and at the same time defines it to be the value of the expression 5.

### Assignment typing

The type of the expression on the right-hand side of the assignment must be assignable to the type of the variable being declared. For example, it is legal to have

real sum = 0;

even though 0 is of type int and sum is of type real, because integer-typed scalar expressions can be assigned to real-valued scalar variables. In all other cases, the type of the expression on the right-hand side of the assignment must be identical to the type of the variable being declared.

Variables of any type may have values assigned to them. For example,

matrix[3, 2] a = b;

declares a $$3 \times 2$$ matrix variable a and assigns a copy of the value of b to the variable a. The variable b must be of type matrix for the statement to be well formed. For the code to execute successfully, b must be the same shape as a, but this cannot be validated until run time. Because a copy is assigned, subsequent changes to a do not affect b and subsequent changes to b do not affect a.

### Right-hand side expressions

The right-hand side may be any expression which has a type which is assignable to the variable being declared. For example,

matrix[3, 2] a = 0.5 * (b + c);

assigns the matrix variable a to half of the sum of b and c. The only requirement on b and c is that the expression b + c be of type matrix. For example, b could be of type matrix and c of type real, because adding a matrix to a scalar produces a matrix, and the multiplying by a scalar produces another matrix.

Similarly,

complex z = 2 + 3i;

assigns the the complex number $$2 + 3i$$ to the complex scalar z. The right-hand side expression can be a call to a user defined function, allowing general algorithms to be applied that might not be otherwise expressible as simple expressions (e.g., iterative or recursive algorithms).

### Scope within expressions

Any variable that is in scope and any function that is available in the block in which the compound declaration and definition appears may be used in the expression on the right-hand side of the compound declaration and definition statement.