“const"如何?C 和 C++ 的区别?

2022-01-23 00:00:00 c constants c++

变量的 const 限定在 C 和 C++ 中有何不同?

How does the const qualification on variables differ in C and C++?

来自:是否const"只是意味着只读还是更多?

引发这个问题的是这个答案:https://stackoverflow.com/questions/4024318#4024417 其中他说 const just"在 C 中表示只读.我认为这就是 const 的全部含义,无论是 C 还是 C++.他是什么意思?"

"What prompted this question was this answer: https://stackoverflow.com/questions/4024318#4024417 where he states const "just" means read-only in C. I thought that's all const meant, regardless of whether it was C or C++. What does he mean?"

推荐答案

const 在 C 中不能用于构建常量表达式.

const in C cannot be used to build constant expressions.

例如:

#include <stdio.h>
int main()
{
   int i = 2;
   const int C = 2;
   switch(i)
   {
      case C  : printf("Hello") ;
      break;

      default : printf("World");
   }
}

在 C 中不起作用,因为 case 标签不会减少为整数常量.

doesn't work in C because case label does not reduce to an integer constant.

相关文章