Hi all
I'm new in the arduino universe and came up with the following question: are the nested functions (subfunctions) allowed in the arduino IDE? If yes, how to do it properly?
I just would like to do repeatable things with the array that is locally defined in some function. I'm thinking to move the repeating code into sub-function like in the example above and use it as many times as I need.
Am I doing something wrong or function declaration inside a function declaration is not supported?
are the nested functions (subfunctions) allowed in the arduino IDE?
What do you mean by allowed?
The functions must be declared separately but can be nested when called. The exception on this is recursion where you call the function you are defining.
Thank you all, guys, for your explanations.
Obviously I understand that I can call declared functions in any sequence/order/depth.
As I do not have much C/C++ experience (I came to programming through pascal/delphi and now I'm using matlab ~80% of the time) when playing with arduino I'm still thinking in pascal style doing on-the-fly translation to C/C++. That's one of the main sources of my mistakes/problems and that's why I was wandering if I can do nested function declaration. Finally, I survived by moving all data to global area and rewriting my code accordingly.
It's not necessary to use globals exclusively - look at the static modifer which permits a function to have local persistent variables. Also pointers and references.
wildbill:
C/C++ do not permit nested functions - hence the error you're getting.
Neither the C nor the C++ standards allow nested functions that can access the variables in the parents lexical scope. The GNU C compiler does have an extension that allows you to define nested function, but the C++ compiler does not support this extension, so you cannot use it for Ardunio programs normally. Also, nested functions cannot be done on some architectures if it is impossible to create code that is executed on the stack. I don't recall if the AVR has such a restriction.
The usual way to do this is to define the values in a structure or class and pass pointers to that value. Beyond just passing a pointer, you could use the class/subclass/virtual function support in C++ to achieve what you want.