Path: csiph.com!weretis.net!feeder6.news.weretis.net!news.misty.com!news.iecc.com!.POSTED.news.iecc.com!nerds-end From: "marb...@yahoo.co.uk" Newsgroups: comp.compilers Subject: Re: Using a C struct to represent a node in a parse tree ... how many fields in the struct? Date: Sat, 9 Apr 2022 05:03:55 -0700 (PDT) Organization: Compilers Central Lines: 34 Sender: news@iecc.com Approved: comp.compilers@iecc.com Message-ID: <22-04-008@comp.compilers> References: <22-04-002@comp.compilers> <22-04-006@comp.compilers> Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Injection-Info: gal.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="75509"; mail-complaints-to="abuse@iecc.com" Keywords: design, comment Posted-Date: 09 Apr 2022 12:05:56 EDT X-submission-address: compilers@iecc.com X-moderator-address: compilers-request@iecc.com X-FAQ-and-archives: http://compilers.iecc.com In-Reply-To: <22-04-006@comp.compilers> Xref: csiph.com comp.compilers:2975 Hmm! The last time I wrote a (simple) compiler, it never occurred to me to use any of those methods! Here's my code (with the 'payload' removed from the struct and new_node): I guess Johann would say I'm being extremely anal :-D struct tree { enum token_type type; struct tree *child, *sibling; }; static struct tree *new_node(int type) { struct tree *res=malloc_or_bomb(sizeof *res); res->type=type; res->child=res->sibling=NULL; return res; } static struct tree *add_child(struct tree *parent, struct tree *child) { /* Add child to end of parent's list of children. */ struct tree **p; for (p=&parent->child; NULL!=*p; p=&(*p)->sibling) ; *p=child; return child; } static struct tree *add_first_child(struct tree *parent, struct tree *child) { /* Add child to start of parent's list of children. */ child->sibling=parent->child; parent->child=child; return child; } (I think I pinched the child/sibling technique for storing trees with arbitrary numbers of children from an Infocom game!) [The child/sibling approach is the way Lisp lists have worked since the last 1950s. For reasons related to the architecture of the IBM 709, they're usually spelled CAR and CDR. -John]