数组初始化在 C++ 中使用 const 变量

Array initialization use const variable in C++(数组初始化在 C++ 中使用 const 变量)
本文介绍了数组初始化在 C++ 中使用 const 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 这可以工作:

  1. this can work:

const int size = 2;
int array[size] = {0}; 

  • 这有编译错误:

  • this has compile error:

    int a = 2;
    const int size = a;
    int array[size] = {0};
    

  • 为什么?

    推荐答案

    因为 C++ 委员会的人是这么决定的.

    Because the guys in the C++ committee decided so.

    技术原因是用于初始化size的第一个表达式是一个常量表达式,它可以在编译期间计算.这意味着编译器还可以知道数组的大小,并且可以在编译时完成分配(在这种情况下保留"可能是更合适的术语).

    The technical reason is that the first expression that is used to initialize size is a constant expression and it can be computed during compilation. This means that the compiler can also know how big the array is going to be and the allocation (in this case "reservation" may be a more appropriate term) can be done at compile time.

    在第二种情况下,表达式不是常量表达式(给定 C++ 定义),并且这种恢复是不可能的.

    In the second case instead the expression is not a constant expression (given the C++ definition) and this revervation is not possible.

    在第二种情况下,值确实在 size 初始化时固定,这一事实完全无关紧要.规则基于表达式的种类",第二个表达式使用可变变量,因此编译器认为它是非常量的.

    The fact that in the second case the value is indeed fixed by the time size is initialized is totally irrelevant. The rules are base on the "kind of expression" and the second expression uses mutable variables and thus the compiler considers it non-constant.

    允许编译时初始化的第二种形式需要流分析,因为它需要区分

    Allowing the second form for compile-time initialization would require a flow analysis because it would need to distinguish between

    int a = 2;
    const int size = a;
    

    int a = foo();
    const int size = a;
    

    其中涉及 size 的表达式确实是相同的.

    where the expression involving size is indeed identical.

    这篇关于数组初始化在 C++ 中使用 const 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

    本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

    相关文档推荐

    Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
    How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
    OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
    How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
    What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
    Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)