本文介绍了为什么不允许使用const的可变大小的对象初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是错误的,因为可变大小的对象可能未初始化

This is wrong since a variable sized object may not be initialized

int size = 4;
int array[size] = {1};

size 是一个变量,编译器在创建数组(不是 size 时间?)?之后,让 size 更改为什么会是一个问题?我的意思是,这些是连续的指令,在声明数组之前,可能会改变 size 的值?

size is a variable, but doesn't the compiler know its value when it creates array (Isn't size assigned an initial value of 4 at compile-time?)? Let size change after that, why would it be an issue? I mean, these are consecutive instructions, what could possibly alter the value of size before the array is declared?

第二个问题:
为什么不允许这样:

Second question:Why is this not allowed:

const int size = 4;
int array[size] = {1};

我将 size 声明为const。我知道const!=只读,并且声明 size 作为宏是正确的方式去做它。但是如果我保证编译器使用const不改变 size 的值,为什么不允许?

I am declaring size as a const. I know that const != read-only, and that declaring size as a macro is the correct way to go about it. But if I promise the compiler using const that I wont change the value of size, why is it not allowed?

推荐答案

第一个问题的答案是因为语言规范说。虽然编译器可以能够推断数组的大小,但这样做需要一些静态分析,当数组大小不是编译时常数表达式时,这是不重要的。

The answer to the first question is "because the language specification says so". Although a compiler may be able to infer the size of the array, doing so requires some static analysis which is not trivial when the array size is not a compile-time constant expression.

至于为什么不允许VLA的初始化:一个原因你的编译器生活在一个洞穴中(例如,微软的工程师们 - 他们的C编译器是广泛使用的编译器的一个罕见例子, the writers of your compiler are living in a cave (for example, the engineers over at Microsoft do -- their C compiler is one rare example of a widely used compiler that still does not support C99, 15 years after its standardization.). Any modern, decent C compiler should enable you to use variable-length arrays which are present in C99. Compilers that already implement C11 may or may not opt to support VLAs (as it's an optional feature of the latest standard).

这篇关于为什么不允许使用const的可变大小的对象初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:10
查看更多