-2

While answering my question in codereview.stackexchange, it was suggested to use,

template <class T, size_t size>
T peak(const T (&arr)[size]) {

Instead of,

int peak(int * arr, size_t size)
{

Now I have two questions here,

  1. How compiler can calculate size, while C++ compiler cannot bound check
  2. What if I use arr[size] instead of (&arr)[size]. I mean is there anything like (arr&)[size]. If yes, what is the difference.
Community
  • 1
  • 1
Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
  • 1
    possible duplicate of [How does this "size of array" template function work?](http://stackoverflow.com/questions/3368883/how-does-this-size-of-array-template-function-work) – syntagma Sep 20 '15 at 07:29
  • 2. A function parameter `int arr[size]` is the same as `int* arr`. There are plenty of questions here that explain that. – juanchopanza Sep 20 '15 at 07:51

1 Answers1

1

In the first case, you pass the array by reference. The function will only accept arrays (and not pointers). Arrays are always of known size, which is known by the compiler and unpacked in the template parameters.

In the second case, you can pass any pointer or array (the latter will decay to a pointer), but you have to specify the size since the compiler cannot infer the size of the memory a pointer points to.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • If size of array is known to compiler why compiler is not able to do bound check in cases like iterating through array in loop. – Pranit Kothari Sep 20 '15 at 07:47
  • @PranitKothari It can actually do this, you can iterate `int arr[3]{1,2,3}; for(auto&& elem: arr) std::cout << elem;`. – vsoftco Sep 20 '15 at 07:50