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
1 Answer 1
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.
-
Note that pass-as-const-reference is often the best alternative to pass-as-value.Edgar Bonet– Edgar Bonet2018年05月04日 10:26:00 +00:00Commented May 4, 2018 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– Majenko2018年05月04日 10:27:37 +00:00Commented May 4, 2018 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– Edgar Bonet2018年05月04日 11:03:48 +00:00Commented May 4, 2018 at 11:03
-
@EdgarBonet Indeed. But if it's getting that complex maybe it's time to consider upgrading to using classes... ;)Majenko– Majenko2018年05月04日 11:05:13 +00:00Commented May 4, 2018 at 11:05
-
ah struct! perfect thanks! I was searching for 'record' as that's what it's called in Delphi....Hamish_Fernsby– Hamish_Fernsby2018年05月05日 08:51:04 +00:00Commented May 5, 2018 at 8:51
Wiring
is the development platform, not the language. We write our sketches in C/C++. Do you meanstruct
or class members in C++? (tutorialspoint.com/cplusplus/cpp_classes_objects.htm)