Sujet : Re: That depends... (Was: Regarding assignment to struct)
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.cDate : 03. May 2025, 05:31:14
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20250502211854.795@kylheku.com>
References : 1 2 3 4
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2025-05-03, Lew Pitcher <
lew.pitcher@digitalfreehold.ca> wrote:
If it is legal, then why isn't it used more often? Is it a readability/
maintainability issue, or is it something else?
It's not used more often because
- programmers are irrationallyafraid that there will be lots of
overhead when the structure gets large.
(In fact, passing large structs by value is implemented
using a hidden pointer; a copy is not made unless the calee
modifies the parameter. Returning likewise: caller passes
a pointer to a location where to place the structure.
It is not as bad as you might think.)
Some of the fear is rational: you usually have a very good
idea how pointer passing is implemented, but not necessarily how
struct passing is.
- some structures cannot be copied; duplicating objects can
be nontrivial when they manage resources or are sensitive
to their own address (like have pointers to parts of themselves).
E.g. you can't just have a FILE parameter and pass (*stdout) to it.
Under object-based/oriented programming in C, we usually pass
around pointers to objects. Treating OOP objects by value requires
techniques found in C++: you need handlers to be invoked when
objects are copied ("copy constructors").
- ABI concerns might prevent you from writing a public API that has
functions that take and/or return structs by value for fear of
causing complications to FFI users, or incompatibilities when
differnet compiler are used.
(We have such APIs in ISO C, though: ldiv and friends.)
(In POSIX, I seem to recall, some platforms have made pthread_t a
struct. Glibc on Linux might have had it that way? I think it's an
unsigned int or long now. Anyway, in those implementations,
pthread_equal takes two structs by value. And, aha, that's why there
is pthread_equal; because pthread_t types might not be scalar values
comparable with ==: i.e. pointers or integers.)
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca