gpt4 book ai didi

c++ - 有没有办法在声明变量后对其进行 constify ?

转载 作者:太空狗 更新时间:2023-10-29 19:37:37 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Is there some ninja trick to make a variable constant after its declaration?

有时在 C 或 C++ 中,我们有一个可能是 const 的变量,但我们必须用几行代码来初始化它。

有没有办法告诉编译器,从一个函数的某个点开始,一些已经构造的变量必须被视为 const,直到它的作用域结束?

类似于:

int c = 0;
// the value of c is initialized here
switch(someVar) {
case foo: c = 3; break;
case bar: c = 4; break;
default : c = 42; // what else?
}
// now c is constant
ASSUME_CONST_FROM_NOW(c) // some #pragma maybe?

我知道我可以在专用函数中初始化变量。这不是我真正想要的。

另一个例子:

int c = 0; int d = 0;
{ /*some block of code that initializes both c and d jointly*/ }
ASSUME_CONST_FROM_NOW(c, d)

没有函数可以在不创建结构或类的情况下一次返回两个值。

但这样的技巧可能很有用,可以让旧的、蹩脚的代码更容易理解,而无需进行太多重构。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com