The meaning of the syntax is `const char (& x) []`
What is the point of syntax const char (&x)[]
in C ++, is it something like a pointer to pass by reference to a function call?
Is it the same as and const char x[]
which defines x as const char*
? And if both are the same, where should I use const char (&x)[]
instead const char x[]
?
source to share
const char (&)[]
is a reference to a const char array. The exposed expression declares x
as one of them.
This is the same as
const char x[]
this is a link to one of these
... which defines
x
howconst char*
Um, no, let's take a step back.
const char array[5]
declares array
as an array of 5 constant characters. It does not declare a pointer. However, arrays decay easily to pointers in C ++, so for example
void foo(const char *);
// ...
foo(array);
is legal. In fact, arrays decay to pointers so easily, it takes extra care to pass them somewhere without decaying:
template <size_t N>
void bar(const char (&x)[N]);
bar(array);
will indeed get a reference to the array, and as a bonus, let bar
me output the size of the array.
Note that the only useful difference between a pointer and an array is the number of elements - when I quoted you saying const char x[]
I am assuming that there will indeed be a number between the square brackets. If you omit that, it doesn't have any use for a pointer unless you initialize it:
const char x[] = { 'h', 'e', 'l', 'l', 'o' };
will still allow this call bar
to output N=5
even if you've never written a literal 5
in your code.
It can also be used when you want your function to accept a fixed-length array:
void fun(const char (&x)[50]);
It can also be used with multidimensional arrays (but prefer std::vector
or if possible std::array
).
source to share
What is the meaning of the const char (& x) [] syntax in C ++
This syntax means that you want to use an array reference for the constant char.
Is it the same as const char x [], which defines x as const char *?
No, this is not the same, the main difference from const char * is that the size of the array has become part of this type, so you cannot pass an array with a different number of elements.
The main use of an array reference is in a template where the number of elements is less than what is output
source to share