1

I know that if you want to pass an array by reference with a known size you use

void add(char (&arr)[60])

But i only know that the array will be size between 1 and 60 inclusive. Any way to do this?

  • possible duplicate of [Passing an array as an argument in C++](http://stackoverflow.com/questions/763861/passing-an-array-as-an-argument-in-c) – paisanco Jan 20 '15 at 02:49

2 Answers2

3

You can use a template to match any type and any size, and a static_assert to check the size of the array being passed at compile-time :

template<typename T, std::size_t N>
void add(T (&arr)[N])
{
    static_assert(N <= 60, "wrong size");
    // ...
}

Demo

quantdev
  • 23,517
  • 5
  • 55
  • 88
0

other option , without using templates :

void add(char* arr , int size);

Remember that ad-hoc array names are "decaying" to be a pointer to the first element , so one-dimensional array can be passes as a pointer.

David Haim
  • 25,446
  • 3
  • 44
  • 78
  • how exactly passing an array by it's pointer is not pass-by-reference ? – David Haim Jan 20 '15 at 07:21
  • this is your own interpretation to the question. the asker asked how to pass an array by reference without knowing it's size. I'm *NOT* getting into the discussion of what "pass-by-reference" means. passing a pointer to the first element of an array IS considered to by pass-by-reference. – David Haim Jan 20 '15 at 07:26
  • 1
    It seems clear to me that OP wants an actual reference-to-array to be passed according to his example signature. However it *is* my interpretation, and as your answer is technically correct I shall not do more than pointing it out. – Quentin Jan 20 '15 at 07:31