Sujet : Re: Regarding assignment to struct
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 04. May 2025, 22:09:55
Autres entêtes
Organisation : None to speak of
Message-ID : <8734dkozfg.fsf@nosuchdomain.example.com>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13)
Lew Pitcher <
lew.pitcher@digitalfreehold.ca> writes:
Back in the days of K&R, Kernighan and Ritchie published an addendum
to the "C Reference Manual" titled "Recent Changes to C" (November 1978)
in which they detailed some differences in the C language post "The
C Programming Language".
>
The first difference they noted was that
"Structures may be assigned, passed as arguments to functions, and
returned by functions."
>
From what I can see of the ISO C standards, the current C language
has kept these these features. However, I don't see many C projects
using them.
>
I have a project in which these capabilities might come in handy; has
anyone had experience with assigning to structures, passing them as
arguments to functions, and/or having a function return a structure?
>
Would code like
struct ab {
int a;
char *b;
} result, function(void);
>
if ((result = function()).a == 10) puts(result.b);
>
be understandable, or even legal?
Struct and union assignment (and argument passing, and returning from
functions) are fundamental features of the C language. You won't
find a C compiler that doesn't fully and correctly support them,
except perhaps ancient compilers from the 1980s or non-conforming
C-like compilers for tiny embedded systems.
There could be potential performance issues passing large structures,
but I wouldn't worry about that unless (a) the structures are
*very* large or (b) you have unusually tight resource constraints.
Someone in this thread suggested avoiding assignment for structs
bigger than twice the size of a pointer, but I'd set the cutoff
substantially higher than that.
For example, in one particular implementation a C++ std::string is
32 bytes and a std::vector is 24 bytes. C++ programmers routinely
pass these by value and copy them, and it doesn't cause any serious
problems. There shouldn't be a problem treating similarly sized
C structs by value. It Just Works.
Of course if you want to pass a structure to a function and have
the function modify it, you need to pass a pointer. You'd do the
same for a scalar parameter.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */