Can Arduino handle variable variables?
function getLetterCode(char input) {
int letter_a = 17;
int letter_b = 42;
int letter_c = 50;
return letter_$$input$$; //pseudocode
}
This is just a stripped down code to demonstrate my question. I am aware of arrays, the switch structure and other workarounds, but for my specific need variable variables would save tons of typing.
1 Answer 1
No, you can't do that sort of thing. That sort of thing is only possible on interpreted languages where the name of the variables is seen at runtime. In compiled languages you can't see the variable names (they no longer exist) so you can't access them by name like that.
Instead you need to either store your variables in a simple array and access them by index, or create an array of "key/value" pairs (simplest to use an array of a struct
) and iterate it looking for the right key to match with your input. Or, if there aren't too many inputs, simply use a switch
to select different values:
int getval(char input) {
switch (input) {
case 'a': return 17;
case 'b': return 42;
case 'c': return 50;
default: return 0;
}
}
-
Thanks! I just realise how much I am used to those high level languages.Zsolt Szilagy– Zsolt Szilagy2019年08月24日 21:52:52 +00:00Commented Aug 24, 2019 at 21:52
-
I know. It's not even as if you can use
Map
in Arduino - the STL is seriously lacking...Majenko– Majenko2019年08月24日 21:56:30 +00:00Commented Aug 24, 2019 at 21:56 -
Point of order: You could also do it in a compiled language with dynamic dispatch (e.g. Smalltalk or Objective-C.)Duncan C– Duncan C2019年08月25日 13:17:42 +00:00Commented Aug 25, 2019 at 13:17
-
@DuncanC I don't count those as real languages.Majenko– Majenko2019年08月25日 13:21:17 +00:00Commented Aug 25, 2019 at 13:21
-
@Majenko well that's silly. Smalltalk is the mother of all Object-oriented languages. So Python is a real language but Smalltalk isn't?Duncan C– Duncan C2019年08月26日 01:05:00 +00:00Commented Aug 26, 2019 at 1:05
letter['a']