Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the following implementation of static_strlen, why are the & and parentheses around str necessary?

If I change the type to const char str[Len], I get the following error:

error: no matching function for call to ‘static_strlen(const char [5])’

Am I correct that static_strlen expects an array of const char references? My understanding is that arrays are passed as pointers anyway, so what need is there for the elements to be references? Or is that interpretation completely off-the-mark?

#include <iostream>

template <size_t Len>
size_t
static_strlen(const char (&str)[Len])
{
  return Len - 1;
}

int main() {
  std::cout << static_strlen("oyez") << std::endl;
  return 0;
}
like image 205
Ben Avatar asked Dec 03 '25 13:12

Ben


1 Answers

No, the function parameter is a reference to an array of Len const chars. That's how the function knows the length (assuming the last byte is a NUL terminator, hence the -1). The parentheses are there precisely to stop it being what you think it is.

Actually there's no such thing in C++ as an array of references, so it couldn't be what you think it is even without the parens. I guess (but am not sure) that the need for the parens is just for consistency with other similar type definitions, such as pointers to arrays:

void fn(const char *a[3]); // parameter a is of type const char**, the 3 is ignored.
void fn(const char (*a)[3]; // parameter a is a pointer to an array of 3 const chars.

That example also illustrates why an array is not a pointer. Predict the output of the following program, and then run it:

#include <iostream>

void fn(const char (*a)[3]) {
    std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}

void fn2(const char *a[3]) {
    std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}

int main() {
    const char a[3] = {};
    const char **b = 0;
    fn(&a);
    fn2(b);
}

#if 0 
// error: declaration of `a' as array of references
void fn3(const char & a[3]) {
    std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}
#endif
like image 54
Steve Jessop Avatar answered Dec 05 '25 01:12

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!