有没有更好的方法在赋值后将变量强制转换为'const'?

Nyb*_*ble 3 c

我总是const用来保护不应该分配的值.无论如何,在某些情况下,我可能需要初始化变量,然后const在同一函数中将其用作值.例如:

void foo() {
  int flags;
  /* ... */
  if (condition1) 
      flags |= 1;
  /* .... */
  if (conditionX)
      flags |= Y;
  /* .... */
  // start using flags as a const value
  const flags; // <<= I want something like this.
  const int c_flags = flags; // <<= What I have to do. The naming is annoying.
  /* ... */
}
Run Code Online (Sandbox Code Playgroud)

有没有办法改善这个?可以是编码样式或高级语言功能.


从@Potatoswatter:对于gcc/clang中的C(gnu样式,比方说,-std = gnu11),可以使用Statement Expression.

foo() {
  const int flags = ({
    int f = 0;
    if (X) f |= Y;
    /* ... update f ... */
    f;
  });
  /* use the `const` flags */
}
Run Code Online (Sandbox Code Playgroud)

nsu*_*ron 9

考虑创建一个返回所需值的函数

const int flags = getFlags();
Run Code Online (Sandbox Code Playgroud)

或者更多面向对象创建一个在构造函数中执行该操作的标志类.

const Flags flags(condition1, ...);
Run Code Online (Sandbox Code Playgroud)


Pot*_*ter 9

在C++中,您可以通过调用lambda表达式来初始化变量:

const int flags = [&] {
    int flags = 0;

    if (condition1) 
        flags |= 1;
    ....
    if (conditionX)
        flags |= Y;

    return flags;
}();
Run Code Online (Sandbox Code Playgroud)

在任何一种语言中,GCC和Clang(以及其他与GCC兼容的编译器)都具有与扩展类似的功能:

const int flags = ({
    int flags = 0;

    if (condition1) 
        flags |= 1;
    ....
    if (conditionX)
        flags |= Y;

    flags;
});
Run Code Online (Sandbox Code Playgroud)