编译时常量

编译时常量 (Compile Time Constant) 是可以在编译时计算的值。编译时常量有四种类型。

  • 常量,比如数字、布尔值、bytes
  • 归纳变量
  • 合约的静态常量属性,用常量初始化
  • 静态常量函数参数

有几种情况只允许使用编译时常量。

  • 循环限制
  • 数组大小
  • 使用 索引运算符 写入数组元素
  • 声明为 static const [1] 的函数参数,例如 reverseBytes(bytes b, static const int size)repeat(T e, static const int size) 中的 size
contract CTC {
    static const int N = 4;
    static const int LOOPCOUNT = 30;

    // A is not a CTC because the right hand size is an expression, not a literal
    static const int A = 2 + 1;
    // B is not a CTC because it is not static
    const int B;

    // FC is a CTC declared in function parameters
    // it can be used within this function, including parameters after it & return type
    function incArr(static const int FC, int[FC] x) : int[FC] {
        loop(FC): i {
            x[i] += i; // induction variable CTC
        }
        return x;
    }

    public function unlock(int y) {
        int[N] arr0 = [1, 2, 3, 4];
        // use `N` to initialize CTC parameter `FC` of function `incArr`
        int[N] arr1 = this.incArr(N, repeat(1, N));
        loop(N) : i {
            require(arr0[i] == arr1[i]);
        }

        int z = 0;
        loop (LOOPCOUNT)
        {
            if (z<y) z += 4;
        }
        require(y == 1);
    }
}
[1]注意:顺序很重要:声明函数参数时不允许使用 const static,但在声明属性时允许。