0

I'm writing a sketch which does some calculations on measured variables, and it's based on a similar program written in Java like c = A.Ux + B.Uz; Where A&B have various parameters Ux,Uy,Uz etc In Delphi this notation can be used either for parameters of classes or variables in a group. Looks like there's something similar in Java. It's a tidy way to organise and manipulate variables when there are lots of them and move them between methods without having huge numbers of arguments.

Is there any way to do this in the Arduino Wiring language? I don't seem to find anything online, but I'm probably phrasing the question wrong. Thanks in advance, Brian

2

What you are looking for is a struct:

struct foo {
    uint8_t Ux;
    uint8_t Uy;
    uint8_t Yz;
};

Then:

struct foo A;
struct foo B;

And:

A.Ux = 3;
B.Uz = 48;

int c = A.Ux + B.Uz;

When calling a function you should really use either pass-as-pointer or pass-as-reference to avoid unnecessary copying:

// By Reference
int normal(struct foo &arg) {
    return (arg.Ux + arg.Uy + arg.Uz) / 3;
}

int avg = normal(A);

Or:

// By pointer
int normal(struct foo *arg) {
    return (arg->Ux + arg->Uy + arg->Uz) / 3;
}

int avg = normal(&A);

You can read more about structs here.

| improve this answer | |
  • Note that pass-as-const-reference is often the best alternative to pass-as-value. – Edgar Bonet May 4 '18 at 10:26
  • @EdgarBonet Unless you want to modify but discard the values. Maybe do some calculations on them and return the result, but want to (for some reason) modify the actual values as part of the calculation process (maybe you're working iteratively on the values and want to accumulate changes, I dunno...). – Majenko May 4 '18 at 10:27
  • Of course there are many specific situations! But that's not my point. My point is that, if you want to optimize a code that mindlessly passes a big struct by value, you know that the caller's copy of the struct should not be modified by the callee. Thus your best bet is to attempt to pass by const reference. If it compiles, you are all good. If it doesn't, that's because the callee is modifying its own copy, and you then know that at least some copying is necessary. – Edgar Bonet May 4 '18 at 11:03
  • @EdgarBonet Indeed. But if it's getting that complex maybe it's time to consider upgrading to using classes... ;) – Majenko May 4 '18 at 11:05
  • ah struct! perfect thanks! I was searching for 'record' as that's what it's called in Delphi.... – Hamish_Fernsby May 5 '18 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.