Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference which doesn't reference anywhere?

Tags:

c++

Following code snippet:

int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
int(&row)[4] = ia[1];

enter image description here

I can't get my head around why this particular code is valid. For my current understanding I don't have a rational explanation. Can someone help me out with that? My problem is with &row which doesn't seem to reference anywhere. My only explanation is that this has to be valid because its an initialisation.

I've got the following explanation from my book:

.... we define row as a reference to an array of four ints

Which array? The one we are about to initialise?

like image 422
HansMusterWhatElse Avatar asked Nov 05 '15 08:11

HansMusterWhatElse


2 Answers

 int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };

Is an array of 3 elements, each element is an array of 4 ints.

int(&row)[4] = ia[1];

Here the int(&row)[4] part declares a reference named row that can reference an array of 4 ints. the = ia[1] initializes it to reference the second element in the ia array, which is an array of 4 ints.

like image 119
nos Avatar answered Oct 03 '22 06:10

nos


int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };

ia is an array of 3 arrays of 4 int each.

ia[0] is { 0, 1, 2, 3 }.

ia[1] is { 4, 5, 6, 7 }.

ia[2] is { 8, 9, 10, 11 }.

I don't quite understand why you say we would be "about to initialize" it -- at this point, ia is completely initialized.

int(&row)[4] = ia[1];

Spiral rule (start with the identifier...):

row

...is a...

(&row)

...reference...

(&row)[4]

...to an array of four...

int(&row)[4]

...int...

= ia[1];

...initialized by ia[1] (because you have to initialize a reference, no way around it).

So row is now a reference to ia[1], which is of type "array of four int". That's all there is to it.

like image 29
DevSolar Avatar answered Oct 03 '22 06:10

DevSolar