Question of return a class type data with union


(Hokins Liu) #1

Hi all,

I have a question about function return a class with union data.

my code define a class like that:

typedef class test_ {
    int a;
    int b;
    union {
        int c;
        float d;
        } value;
} Test;

then I create a function that return this class:

Test func( int value);

this function will return data of 'a' & 'c' in the union, 'a' always set as a constant "ex: 1", and 'c' will be set as input parameter 'value'

Test func(int value) {
    return (Test) {.a = 1, .value.c = value};

when I build the code, the result print out likes
"expected primary-expression before ")" token"
"expected ';' before '{' token"
"expected promary-expression before '.' token"

and I try to using mbed class online complier (not yotta), the function can be complie & the outcome is compling pass.

So, my question is: the function return style is illegal in yotta's complier rule or not?


(Jan Jongboom) #2

This is an interesting one. It's not valid code according to gcc 4.8 and gcc 5.3, but Apple LLVM 7.0.2 compiles it fine.

I'm fairly sure that on mbed Classic we use armcc to compile, whereas on yotta it depends on your target (but presumably you're using a gcc target), so it could be that armcc also implements this construct, which explains this behavior. Unfortunately I don't have an armcc copy laying around, so I can't verify.

If you have a license for armcc, switching to an armcc target would be the easiest.

(Hokins Liu) #3

Hi ianjongboom,

Unfortunately, I have no license for armcc too, so I can't verify the result of compiling using armcc by yotta.

but In this case, If I want to return the same result like this example by using gcc, do you know how to modify the code to implement that on gcc compiling?

(Jan Jongboom) #4

Not in a short way, but this works:

Test func(int value) {
    Test t;
    t.a = 1;
    t.value.c = value;
    return t;

(Hokins Liu) #5

Thank you, janjongboom.

I think it's the solution to do that, and I have a new question about running this solution by gcc & past example in armcc.

If we using this solution in gcc, when ARM (like K64F) running into this function. the function looks like create a new private memory size for Test class, named "t'.

if we using the past example code with armcc, does the memory size be created too?

(Jan Jongboom) #6

I'm pretty sure both of these compile the same. Both variables are created on the stack, and use the same amount of memory (12 bytes presumably).

Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.