const and struct pointers
Will Crowder
will at charyb.COM
Sun Feb 25 05:15:26 AEST 1990
In article <90054.232325CMH117 at psuvm.psu.edu> CMH117 at psuvm.psu.edu
(Charles Hannum) writes:
>
>The double is passed by value; so dereferencing it works fine. But the
>struct is passed by reference (as are *all* structures in C!). In reality,
>you need to pass a "struct qwert *" to the function. Normally, the compiler
>takes the reference automatically, but you are trying to do this in reverse.
>Thus, it does not work; you simply can't pass a structure by value.
Uh, yes you can. The man is using what claims to be an ANSI C compiler
(apparently, a slightly broken one), and there is nothing special about
structure objects in ANSI C (at least in terms of how they are passed to
a function).
>From 3.1.2.5 of the 12/88 draft:
"Any number of derived types can be constructed from the object,
function, and incomplete types, as follows:"
...
"* A structure type describes a sequentially allocated nonempty
set of member objects, each of which has an optionally specified
name and possibly distinct type."
The point is, a structure is an object just like any other object; there
is no special constraint on it of the type you describe.
The draft Standard goes on to describe what happens on entry to a function:
Section 3.7.1:
"On entry to the function the value of each argument expression
shall be converted to the type of its corresponding parameter, as if
by assignment to the parameter. Array expressions and function
designators as arguments are converted to pointers before the call."
Structures are neither array objects nor function objects, and thus may
be passed by value.
gcc -pedantic -Wall -c his.c.file.c -o /dev/nul
produces no warnings or errors for his code. However, Turbo C 2.0 seems
to have the problem he is describing:
Warning [...]: Structure passed by value...
Error [...]: Type mismatch in parameter 'a' in call to 'asdf'...
Changing the prototype to "const struct qwert a" fixes the error, but does
not remove the warning. The compiler is warning that it specifically *is*
an ANSI C compiler, and will pass structures by value unless told to do
otherwise with the & operator. UNIX compilers traditionally converted
such references to pointers, so if someone is using Turbo C to port
some UNIX code, this is a very useful warning.
Actually, I'm somewhat surprised that Turbo C didn't just throw out the
"const" in:
void asdf(const struct qwert a);
I wouldn't think "const" would mean much for a non-pointer parameter passed
by value.
Will
More information about the Comp.lang.c
mailing list