gpt4 book ai didi

c++ - 我可以在 case 语句中使用数组吗?

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

我想在 C++ 的 switch/case 语句中使用一个 const int 数组。是否可以?到目前为止,我已经尝试过类似的方法:

int main()
{
int const tab[3] = {1,2,3};
int value(2);
switch(value)
{
case tab[1]:
cout << "result is: " << tab[0]<< endl;
}
return 0;
}

但是编译器一直告诉我:

.../main.cpp|11|error: the value of ‘tab’ is not usable in a constant expression

好吧,我将我的数组声明为“int const”,这还不够吗?

最佳答案

每个 case 语句都必须采用一个常量表达式,其定义为:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

  • [...]
  • an lvalue-to-rvalue conversion (4.1) unless it is applied to
    • a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression [ Note: a string literal (2.14.5) corresponds to an array of such objects. —end note ], or
    • a non-volatile glvalue that refers to a non-volatile object defined with constexpr, or that refers to a non-mutable sub-object of such an object, or
    • a non-volatile glvalue of literal type that refers to a non-volatile object whose lifetime began within the evaluation of e;
  • [...]

您的情况是左值到右值的转换,但这三个要点都不适用,因此 tab[1] 不是核心常量表达式。然而,第二个子项目符号点为我们提供了一个线索:如果对象是用 constexpr 定义的会怎样!这将使 tab[1] 成为一个常量表达式,因此,编译:

constexpr int tab[3] = {1,2,3};
int value(2);
switch(value)
{
case tab[1]:
cout << "result is: " << tab[0]<< endl;
}

const 不会使对象成为常量表达式。它只是使它不可变。请注意,以下是完全有效的代码:

int x;
cin >> x;
const int y = x; // obviously, y can't be a constant expression

关于c++ - 我可以在 case 语句中使用数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30549819/

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