1

I have a problem with the initialization with various parameters in my function. It works if I have created an array int params [] = {...}. However, it doesn't work if I want to write the parameters directly into the function.

declaration (in the .h)

void phase_an(int led[]);

in the .cpp

void RS_Schaltung::phase_an(int led[])
{
  for (size_t i = 0; i < LEN(led); i++) {
    digitalWrite(led[i], HIGH);
  }
}

if I try this way, it won't work. I would like it to be like that. But I couldn't find anything about it on the internet. ...: in the Arduino sketch:

RS.phase_an(RS.ampelRot, RS.ampelGelb, ..... );    <--- is there a way to do it like that?

what amazes me is that it works this way:

int p_an [5] = {RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb};
...................
RS.phase_an (p_an);

does anyone have a suggestion?

BanAnn
  • 159
  • 1
  • 7

1 Answers1

1

There are several ways of making a function accepting a variable number of arguments here.

However, in your current code there is a problem: when you pass a native array of unknown size as argument of a function (e.g. void f(int a[])), the argument will be managed a pointer to an array, and there is no way inside this function to know the real length of that array. I don't know how LEN() is defined, but chances are high that it doesn't works well in your code.

A safer and more practical alternative is to use a vector<int> instead:

#include <iostream>
#include <vector>
using namespace std;

void f(const vector<int>& a){
    for (int i=0; i<a.size(); i++) {
        cout<<a[i]<<" ";
    }
    cout<<endl; 
}

int main() {
    vector<int> test={1,2,3,4}; 
    f(test); 
    f({1,2,3,4});
    return 0;
}

In this case, you can pass your multiple values between bracket in the function call (e.g. ({RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb})and C++ will automatically convert it to a vector.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • thanks a lot. it works. I did `LEN` by define a preprocessor this way: `#define LEN(x) (sizeof(x)/sizeof(*(x)))` – BanAnn Dec 11 '21 at 16:53
  • @BanAnn That’s what a suspected. It works only on arrays of a known size. Otherwise: it returns an implementation defined value that has nothing to do with the real length of the array. The best approach is to use vectors instead of arrays. Passing them by reference is as efficient as passing a pointer. If nevertheless you’d prefer arrays, you’d always need to pass a second parameter for the length if it’s dynamic. – Christophe Dec 11 '21 at 18:24
  • thanks for the hint. Yes, I removed `LEN` and replaced it with .size () after` #include `. Then I added `typedef` to the header and it worked. But I'll try that with the arrays, so thank you for your information. – BanAnn Dec 11 '21 at 20:28