Reputation: 73
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.
Upvotes: 1
Views: 392
Reputation: 204886
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.
Upvotes: 8
Reputation: 100718
This creates an array of 3 integers. You're right, there is no difference whether you express it as2 + 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.
Upvotes: 0
Reputation: 28184
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.
Upvotes: 0
Reputation: 54345
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.
Upvotes: 0
Reputation: 103535
How is that different from
int var[3]
?
In no way that I can see.
Upvotes: 0
Reputation: 39419
It is any different from int var[3]
. The compiler will evaluate 2 + 1
and replace it with 3
during compilation.
Upvotes: 0