简体   繁体   English

C ++编译时表达式作为数组大小

[英]C++ compile-time expression as an array size

I'm not sure if the term's actually "Array Addition". 我不确定该术语是否实际上是“数组加法”。

I'm trying to understand what does the following line do: 我试图了解以下行的作用:

int var[2 + 1] = {2, 1};

How is that different from int var[3] ? int var[3]有何不同?

I've been using Java for several years, so I'd appreciate if explained using Java-friendly words. 我已经使用Java几年了,因此,如果使用Java友好的单词进行解释,我将不胜感激。

Edit: Thousands of thanks to everyone who helped me out, Occam's Razor applies here. 编辑:感谢所有帮助我的人,Occam的Razor在这里适用。

It's not different. 没什么两样 C++ allows expressions (even non-constant expressions) in the subscripts of array declarations (with some limitations; anything other than the initial subscript on a multi-dimensional array must be constant). C ++允许在数组声明的下标中使用表达式(甚至是非常数表达式)(有一些限制;多维数组上除初始下标以外的任何其他内容都必须是常量)。

int var[];  // illegal
int var[] = {2,1};  // automatically sized to 2
int var[3] = {2,1};  // equivalent to {2,1,0}: anything not specified is zero
int var[3];  // however, with no initializer, nothing is initialized to zero

Perhaps the code you are reading writes 2 + 1 instead of 3 as a reminder that a trailing 0 is intentional. 可能是您正在阅读的代码写的是2 + 1而不是3 ,以提醒您尾随0是有意的。

How is that different from int var[3] ? int var[3]有何不同?

In no way that I can see. 我绝对看不到。

It is any different from int var[3] . 它与int var[3] The compiler will evaluate 2 + 1 and replace it with 3 during compilation. 编译器将评估2 + 1并在编译过程中将其替换为3

var[2 + 1] is not different from var[3] . var[2 + 1]var[3] The author probably wanted to emphasize that var array will hold 2 data items and a terminating zero. 作者可能想强调一下,var数组将包含2个数据项和一个终止的零。

It isn't any different; 没什么不同; it is int var[3] . 它是int var[3]

Someone might write their array like this when writing char arrays in order to add space for the terminating 0 . 有人在写char数组时可能会这样写他们的数组,以便为​​终止0添加空间。

char four[4 + 1] = "1234";  

It doesn't seem to make any sense working with an int array. 使用int数组似乎没有任何意义。

This creates an array of 3 integers. 这将创建一个由3个整数组成的数组。 You're right, there is no difference whether you express it as 没错,无论您表达为
2 + 1 or 3 , as long as the value is compile-time constant. 2 + 13 ,只要该值是编译时常数即可。

The right side of the = is an initializer list and it tells the compiler how to fill the array. =的右侧是一个初始化列表,它告诉编译器如何填充数组。 The first value is 2 , the second 1 and the third is 0 since no more values are specified. 第一个值为2 ,第二个为1 ,第三个为0因为没有指定更多的值。

The zero fill only happens when you use an initializer list. 零填充仅在使用初始化程序列表时发生。 Otherwise there is no guarantee of that the array has any particular values. 否则,不能保证该数组具有任何特定值。

I've seen this done with char arrays, to emphasize that one char is reserved for a string terminator, but never for an int array. 我已经看过用char数组完成此操作,以强调一个char是为字符串终止符保留的,但从未为int数组保留的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM