RETURN mixed with FUNCTION =

General FreeBASIC programming questions.
Post Reply
VANYA
Posts: 1834
Joined: Oct 24, 2010 15:16
Location: Ярославль
Contact:

RETURN mixed with FUNCTION =

Post by VANYA »

Hi All!

Please tell me why such a limitation in the compiler?

Code: Select all

type A extends object
	i as Long
End Type

function Test() as A
	dim p as A
	p.i = 10
	if 1 then
		p.i = 20
		function = p
	EndIf
	return p
End function

dim p as A = Test()
? p.i
error 178: RETURN mixed with 'FUNCTION =' or EXIT FUNCTION (using both styles together is unsupported when returning objects with constructors), found 'p' in 'return p'
fxm
Moderator
Posts: 12098
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: RETURN mixed with FUNCTION =

Post by fxm »

In case the object to be returned (by value) needs to be actually constructed:
- 'FUNTION' calls the default constructor once, then the copy-let operator at each possible value of 'FUNCTION =' (so the last value wins).
- The first 'RETURN' encountered calls the copy constructor (and the object is immediately returned).
So there can be no concurrency of these 2 syntaxes that would therefore induce 2 distinct objects.

Workaround:
- 'RETURN p' can easily be replaced by 'FUNCTION = p : EXIT FUNCTION'.
- Using the copy constructor only instead of the default constructor plus the copy-let operator, 'RETURN p' can be considered as an optimization of 'FUNCTION = p : EXIT FUNCTION'.

Note: 'RETURN' and 'FUNCTION =' can be mixed regardless of the object when returned by reference.
VANYA
Posts: 1834
Joined: Oct 24, 2010 15:16
Location: Ярославль
Contact:

Re: RETURN mixed with FUNCTION =

Post by VANYA »

Thanks for the clarification fxm!
PaulSquires
Posts: 1001
Joined: Jul 14, 2005 23:41

Re: RETURN mixed with FUNCTION =

Post by PaulSquires »

Thanks fxm, I have also often wondered about the reason for the error message. Good information to know.
Post Reply