vala - Vala 中的局部静态常量 : possible?

标签 vala

土地

Vala 提供枚举。但这些不能在子程序本地定义。常量可以在子程序本地定义,但似乎不被视为静态表达式(伪常量)。

案例

我有一些子程序实现为使用 switch 语句构建的状态机。我使用一些 switch (state) { ... } 并希望在 case 语句中使用一些常量,如 case initial_state: { ... } 。我认为这是推荐的,因为它比使用 case 0: { ... } 中的文字常量更具可读性和可维护性。

我尝试使用 const int initial_state = 0; 等声明在子程序中定义这些常量。但瓦拉对每个案件的陈述都有提示。我尝试为状态定义一个枚举,如 enum State { initial_state, ... };,但 Vala 拒绝这样做,因为这是一个语法错误,并且似乎只允许在子程序之外进行枚举声明。

到目前为止,我必须将所有状态枚举定义为子程序的外部,或者在子程序内部定义常量,但必须使用 if 结构而不是 switch 构造,因为 if 条件表达式可以不是静态的。

问题

Vala 是否允许以某种方式在子程序本地定义静态常量(标量类型)?

最佳答案

这实际上是来自 gcc 的错误,而不是 valac 的错误。使用这个例子:

private void foo (int val) {
  const int one = 1;
  const int two = 2;
  const int three = 3;

  switch ( val ) {
    case one:
      GLib.debug ("One");
      break;
    case two:
      GLib.debug ("One");
      break;
    case three:
      GLib.debug ("Three");
      break;
    default:
      GLib.debug (val.to_string ());
      break;
  }
}

valac 将生成:

void foo (gint val) {
    static const gint one = 1;
    static const gint two = 2;
    static const gint three = 3;
    gint _tmp0_;
    _tmp0_ = val;
    switch (_tmp0_) {
        case one:
        {
            g_debug ("t.vala:8: One");
            break;
        }
        case two:
        {
            g_debug ("t.vala:11: One");
            break;
        }
        case three:
        {
            g_debug ("t.vala:14: Three");
            break;
        }
        default:
        {
            gint _tmp1_;
            gchar* _tmp2_ = NULL;
            gchar* _tmp3_;
            _tmp1_ = val;
            _tmp2_ = g_strdup_printf ("%i", _tmp1_);
            _tmp3_ = _tmp2_;
            g_debug ("t.vala:17: %s", _tmp3_);
            _g_free0 (_tmp3_);
            break;
        }
    }
}

gcc 会说这样的话:

t.vala.c:25:3: error: case label does not reduce to an integer constant
t.vala.c:30:3: error: case label does not reduce to an integer constant
t.vala.c:35:3: error: case label does not reduce to an integer constant

有趣的是,clang 可以使用它(valac --cc=clang ...,如果你想使用它)。

关于vala - Vala 中的局部静态常量 : possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14976883/

相关文章:

Gtk 按钮 override_background_color 在某些主题上不起作用

vala - 控制 Vapi 文件中的 ref 类型

smtp - 如何实现服务器端 SMTP STARTTLS?

gtk - 瓦拉 Gtk 模板 : UI Resource not found

ubuntu - 在 pkg-config 搜索路径中找不到构建验证 : Package libvala-0. 12

c - 瓦拉内存管理

c++ - 如何在 Vala 中使用 C++ 库

java - 我可以使用 Java 为 Elementary OS AppCenter 进行开发吗?

在窗口上创建 "overlay"

grid - 当附加到 Gtk.Grid 时,Gtk.DrawingArea 为空白