Question:
I’m working with a CCS compiler for the PIC16F877, so the rules may be different, but I’ve created my own data structure (named MERIT_long) to support >16bit values (CCS’s largest data-type is a 16bit long); it has an 8bit char(MSB) and a 16bit long(LSB), as well as a 1bit short (rollover flag). I need to return this struct from a function, but the compiler complains.
Do I need to use pointers/references for this? If so, how? I assume this is part of regular C/C++ functionality, and possibly a limitation of the CCS compiler.
Answer:
It’s a compiler-specific limitation. Both ANSI C and C++ allow you to return a struct by value from a function. However, it seems that your compiler uses only a subset of C/C++. This is common practice in embedded systems and controllers. As a workaround, you can return non-primitive data types by reference or by address:
MERIT_long * func() // return pointer{ MERIT_long * p = new MERIT_long; //... assign values return p;}MERIT_long & func() // return reference{ static MERIT_long ml; //... assign values return ml;}