2

I am new to C++ and would like to check what does (&array) trying to represent here.

template <class var, size_t N>
var sum_numbers(var (&array)[N]) {
    var sum = 0;
    for (size_t f1=0; f1<N; f1++) {
        sum = sum + array[f1];
    }
    return sum;
}

If i only need to loop through the array and count the number of occurrence for each loop, do i need to put (&array) or can i just change the code to

template <class var, size_t N>
var sum_numbers(var [N]) {
    var sum = 0;
    for (size_t f1=0; f1<N; f1++) {
        sum = sum +1;
    }
    return sum;
}
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
Ugine
  • 143
  • 8
  • Does that method of passing array as argument even work? – nishantsingh Oct 04 '16 at 09:55
  • Arrays have their own type in C++. Thus `var (&array)[N]` is that you're passing an array of `var` objects of size `N` by reference. – 101010 Oct 04 '16 at 09:57
  • I check this code out from the website, but i have no idea what does the (&array) represent. I am new to C++ and would like to check how can i loop through an array and return the number of occurrence in an array using template function. – Ugine Oct 04 '16 at 09:58
  • @Ugine If you are new to C++, you shouldn't be using templates. – Rakete1111 Oct 04 '16 at 09:59
  • 2
    @Rakete1111: why not? I disagree. – Violet Giraffe Oct 04 '16 at 09:59
  • I disagree with @Rakete1111. It you're new to C++, you shouldn't be using pointers, dynamic allocation, functions that look like they take arrays but take pointers instead... – juanchopanza Oct 04 '16 at 10:00
  • I think this topic falsely marked as duplicate. Author asking about necessarity of this parameter, not about how to pass it to function – Denis Sheremet Oct 04 '16 at 10:05
  • This parameter is necessary unless you explicitly pass typename to function's template. You also may simply return N in your code instead of looping. – Denis Sheremet Oct 04 '16 at 10:07
  • @DenisSheremet Yeah that was my point. Thank you so much for your answer. Really appreciated it! – Ugine Oct 04 '16 at 10:09
  • @DenisSheremet "*would like to check what does (&array) trying to represent here*". It is the syntax for passing an array by reference. The second part wouldn't compile. – juanchopanza Oct 04 '16 at 10:11
  • @Rakete1111 You can’t do even the most rudimentary stuff in C++ without pointers. Case in point, you can’t even pass an array of variable size to a function without templates in C++ (try rewriting OP’s code without templates … it doesn’t work even if you fix `var` to a type). – Konrad Rudolph Oct 04 '16 at 10:13

0 Answers0