Bruno
Bruno

Reputation: 458

How to use structured binding in an array passed as arg to some function?

I'm trying to decompose an array of 2 integers given to a function into x, y

It doesn't work when using int init[2] as a parameter. But it does when I change it to int (&init)[2].

vector<vector<State>> Search(vector<vector<State>> board,
                             int init[2], int goal[2]) {
  auto [x, y] = init;
}

What does (&init) mean here? And why it doesn't work when using int init[2]?

Upvotes: 8

Views: 604

Answers (1)

int (&init)[2] is a reference to an array of two integers. int init[2] as a function parameter is a leftover from C++'s C heritage. It doesn't declare the function as taking an array. The type of the parameter is adjusted to int* and all size information for an array being passed into the function is lost.

A function taking int init[2] can be called with an array of any size, on account of actually taking a pointer. It may even be passed nullptr. While a function taking int(&)[2] may only be given a valid array of two as an argument.

Since in the working version init refers to a int[2] object, structured bindings can work with that array object. But a decayed pointer cannot be the subject of structured bindings, because the static type information available only gives access to a single element being pointed at.

Upvotes: 9

Related Questions