This is an old version, view current version.

5.7 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.

Any type may be assigned. For example,

matrix[3, 2] a = b;

declares a matrix variable a and assigns it to the value of b, which must be of type matrix for the compound statement to be well formed. The sizes of matrices are not part of their static typing and cannot be validated until run time.

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.

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.