简体   繁体   中英

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] ?

I've been using Java for several years, so I'd appreciate if explained using Java-friendly words.

Edit: Thousands of thanks to everyone who helped me out, Occam's Razor applies here.

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).

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.

How is that different from int var[3] ?

In no way that I can see.

It is any different from int var[3] . The compiler will evaluate 2 + 1 and replace it with 3 during compilation.

var[2 + 1] is not different from var[3] . The author probably wanted to emphasize that var array will hold 2 data items and a terminating zero.

It isn't any different; it is int var[3] .

Someone might write their array like this when writing char arrays in order to add space for the terminating 0 .

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

It doesn't seem to make any sense working with an int array.

This creates an array of 3 integers. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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