Path: csiph.com!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: So You Think You Can Const? Date: Wed, 08 Jan 2025 12:12:37 -0800 Organization: A noiseless patient Spider Lines: 46 Message-ID: <86frlt83pm.fsf@linuxsc.com> References: <20250107130809.661@kylheku.com> <87a5c15ob0.fsf@bsb.me.uk> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Date: Wed, 08 Jan 2025 21:12:37 +0100 (CET) Injection-Info: dont-email.me; posting-host="6e19b66cb0c542b6b8c649f7413a0cd9"; logging-data="3071468"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX189ghW5X5FLmoLzgKnia32bRRI9C0n00Ew=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:KyV8KQADzNMxaxeaBOSXanriL9Q= sha1:hrejEVQA5mBOBSckqpaLNnO/xbU= Xref: csiph.com comp.lang.c:389893 Julio Di Egidio writes: [...] > Say my program unit implements AVL trees, with (conceptually > speaking) constructors/destructors, navigation and retrieval, and > of course manipulation (inserting, deleting, etc.). > > My idea (but I would think this is pretty "canonical" and, if it > isn't, I am missing the mark) is: my public functions take/give > "sealed" instances (with const members to const data), as the user > is not supposed to directly manipulate/edit the data, OTOH of > course my implementation is all about in-place editing... A better choice is to put the AVL code in a separate .c file, and give out only opaque types to clients. For example (disclaimer: not compiled): // in "avl.h" typedef struct avl_node_s *AVLTree; // note that the struct contents are not defined in the .h file ... declare interfaces that accept and return AVLTree values ... // in "avl.c" #include "avl.h" struct avl_node_s { // whatever members are needed }; ... implementation of public interfaces and any supporting ... functions needed I might mention that some people don't like declaring a type name that includes the pointerness ('*') as part of the type. I think doing that is okay (and in fact more than just okay; better) in the specific case where the type name is being offered as an opaque type. Of course you could also make the opaque type be a pointer to a 'const' struct type, if you wanted to, but the extra "protection" of const-ness doesn't add much, and might actually cost more than it buys you because of the additional casting that would be needed.