F
F
ForveAvar2015-02-14 11:51:41
Arduino
ForveAvar, 2015-02-14 11:51:41

How to pass an array correctly?

Hello!
How can I pass an array of creations to a function without explicitly declaring a variable, can I do it in javascript as I can
functionCall([0,1,2,3])
do it in c++?
I did this
functionCall(&(int {0,1,2,3}[]))
but I get errors, how should I beat?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2015-02-14
@ForveAvar

On C(90)/C++(98) - no way,
on C++11 - using a function template with a variable number of arguments

template<typename F, typename ...T> void f(F f,T...arr)
{
   std::array<F,1+sizeof...(T)> a{f,...arr};
//........
}

in C++11, fixed size array:
#include <iostream>
#include <array>

using namespace std;

void f(const std::array<int,3> &arr)
{
  for(const auto &v: arr)	
       cout << v << " ";
}

int main() 
{
    f({1,2,3,4,5});
  return 0;
}

in C++11, an array of arbitrary size (but using the heap):
#include <iostream>
    #include <vector>
     
    using namespace std;
     
    void f(const std::vector<int> &arr)
    {
    for(const auto &v: arr)	
    cout << v << " ";
    }
     
    int main()
    {
    f({1,2,3,4,5});
    return 0;
    }

options offered by Don Kaban
on C99
thanks, jcmvbkbc

A
AxisPod, 2015-02-14
@AxisPod

std::initializer_list, although it must be supported by the function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question