C FAQ 2.18

C

ccwork

Hi,
In 2.18 "structure-valued functions are usually implemented by
adding a hidden return pointer". What's that mean??
 
M

Michael Mair

ccwork said:
Hi,
In 2.18 "structure-valued functions are usually implemented by
adding a hidden return pointer". What's that mean??

Often, if you define functions returning structs, the compiler
internally does something different:
struct foo bar (int baz)
{
struct foo tmp;
........
return tmp;
}

void tst (void)
{
struct foo test;
test = bar(42);
}
may be handled as if we had
void bar (int baz, struct foo *p)
{
/* work on *p */
........
}

void tst (void)
{
struct foo test;
bar(42, &test);
}

FAQ 2.18:
"2.18: This program works correctly, but it dumps core after it
finishes. Why?

struct list {
char *item;
struct list *next;
}

/* Here is the main program. */

main(argc, argv)
{ ... }

A: A missing semicolon causes main() to be declared as returning a
structure. (The connection is hard to see because of the
intervening comment.) Since structure-valued functions are
usually implemented by adding a hidden return pointer, the
generated code for main() tries to accept three arguments,
although only two are passed (in this case, by the C start-up
code). See also questions 10.9 and 16.4.

References: CT&P Sec. 2.3 pp. 21-2.
"

With main() being the first function (from our point of view),
there is no way to pass the address of a valid struct foo
object. At return from main(), we are in trouble.
This kind of error usually does not happen if you do not rely on
implicit int.


Cheers
Michael
 
C

ccwork

Hi,
But this is "usually implemented". Does the C standard say anything
about a function returning a struct?
 
M

Michael Mair

ccwork said:
Hi,
But this is "usually implemented". Does the C standard say anything
about a function returning a struct?

Yes; functions accept structures as arguments and can return them.
How this is actually implemented, is completely outside the scope
of the C standard. The explanation was only provided in order to
enable you to understand _why_ it may compile yet crash because
of forgetting a semicolon _and_ forgetting to provide the
return type int for main.

Please do not top-post.

Cheers
Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,609
Members
45,253
Latest member
BlytheFant

Latest Threads

Top