Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass an array into a function as a parameter without creating a variable for that array?

Tags:

c++

So I made a function that takes arrays as parameters and I've tried calling the function by passing arrays that have not been defined as variables into said function (like {0,0,0,0}). However, I am given an error which says "too many initializer values."

Say we have a function defined as:

int func(int values[]) {
  int average = 0;
  for(int x = 0; x < values.size(); x++) {
    average += values[x];
  }
  return average / values.size();
}

And we want to call it without defining an array to pass in like this: func({1,6,7,2});

Is there any way to do something like this or would I have to define an array and pass it into the function that way?

like image 780
Cyerunix Avatar asked Jan 26 '23 13:01

Cyerunix


1 Answers

You cannot do that using built-in arrays. The fact that Arrays are neither Assignable nor Copy-able. Also They are not classes so they don't have member functions like size() or they take Initializer-list.

You can achieve that through using std::array if the size is constant or using std::vector if the size if dynamic.

#include <array>


int func(const std::array<int, 5>& values) { 

    int average = 0;
    for (size_t x{}, sz{ values.size() }; x != sz ; ++x)
        average += values[x];

    return average / values.size();
}



int main() {
    auto ret{
        func({ 1, 6, 7, 2 })
    };

    std::cout << ret << std::endl;
}
  • Also don't mix Unsigned with Signed in calculations like in your loop:

    for(int x = 0; x < values.size(); x++) // x is int while values.size() is unsigned int.
    
  • int func(const std::array<int, 5>& values): pass by reference to avoid the copy especially if the size is big. Also pass by const as long as the function doesn't intend to change the parameter also another benefit of using const reference is you can pass literals instead of an object.

  • N.B: I recommend to also to use range-based for because it is really relevant in your example as long as you want to iterate over all the elements and not intending to insert nor to delete elements:

    int average = 0;
    for (const auto& e : values)
        average += e;
    
  • Another version of func as @M.M pointed out is to use std::accumalate to do the job for you:

    int func(const std::array<int, 5>& values) {    
        return std::accumulate(values.begin(), values.end(), 0) /
            values.size();
    }
    
like image 167
Raindrop7 Avatar answered Feb 16 '23 03:02

Raindrop7