[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Not able to use %union?
From: |
Christian Schoenebeck |
Subject: |
Re: Not able to use %union? |
Date: |
Mon, 18 Feb 2019 12:22:27 +0100 |
User-agent: |
KMail |
On Sonntag, 17. Februar 2019 21:37:26 CET Peng Yu wrote:
> Because I want to use the previously allocated memory, I don't want to
> call "rs_init(&yylval->str)" in any action. So YYSTYPE must be a
> struct instead of a union. Is it a good practice to use struct instead
> of union?
Yes, it is. The only advantage by using a union as a type is that you save
some tiny amount of memory, but a union is also less safe and harder to debug.
So personally I would barely ever use union as fundamental type with Bison.
> Since %union cannot be used in this case, how to deal with this
> scenario in bison? Thanks.
There is actually no difference in usage, since the Bison generated parser
code will access the fields in the same way: simply by using the union/struct
member names you defined (e.g val.num, val.str in your example). So the actual
difference between struct or union is handled by the C/C++ compiler, not by
Bison.
Any reason that you don't want to use C++ and e.g. std::string instead of your
pure C and garbage collector solution?
Best regards,
Christian Schoenebeck