Why this works?

J

James Kanze

AFAIK C++ inherits this optionality of a return value from C. I'm guessing
that it exists in C because in the 70's they didn't want to force the
programmer to increase the size of functions by even one byte if they
absolutely didn't have to.

The rules in C were (and I think still are) slightly different;
falling off the end was only undefined behavior if the callee
tried to use the returned value. Originally, C didn't have
`void`; functions which didn't have anything to return returned
`int`, and the callee just ignored it.

In the case of C++, things start getting more complicated if the
return type has non-trivial constructors and destructors. The
callee is going to call the destructor, even if the coder
ignores the return value.
Nowadays increasing the size of a function by a few bytes due to an
extraneous 'return' might not be a problem, but the thing is, there
might be cases where the 'return' actually takes a lot more than just
a few bytes.
The return value might in fact be very large, like several kilobytes.
*Creating* the return value might be very complicated or laborious
(such as it being an object with a mandatory constructor that takes
hundreds of mandatory parameters.) Being forced to construct such a
complicated object can in some cases be completely unnecessary, for
example in situations like

Constructing a return value might note even be possible, if the
type doesn't have a default constructor. You may not have the
appropriate values.

There *is* a simple solution: just insert an illegal instruction
in the generated code. If the function does fall off the end,
the program crashes.
 

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

Forum statistics

Threads
473,994
Messages
2,570,222
Members
46,810
Latest member
Kassie0918

Latest Threads

Top