Declare Sub Question

New to FreeBASIC? Post your questions here.
Post Reply
mccp1999
Posts: 24
Joined: Jul 03, 2006 23:59
Location: West Sussex

Declare Sub Question

Post by mccp1999 »

I have created a Sub with one parameter (Double) and a default value of 1 as in -
Sub Delay(byref as Double=1)

If I place this at the top of my code then it executes correctly within the rest of the code whether I send a value as in Delay(2)

or I let it use the default value as in Delay

I do not want to put this Sub at the start of the code so I decided to include a Declare Sub at the top
Declare Sub Delay(as Double)

Now it will not compile unless I pass a value as in Delay(2) above
and if I use Delay on its own gives a 'Argument count mismatch' error

Am I doing something wrong? Thanks for your help
fxm
Moderator
Posts: 12081
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Post by fxm »

In order to simplify the programming, I advise you to have the declaration line and the line defining the subroutine identical in terms of passing parameters.

Declare Sub Delay(ByRef seconds As Double=1)
. . . .
. . . .
Sub Delay(ByRef seconds As Double=1)
. . . .
. . . .
End Sub



Remark :
The minimum wording would be:

Declare Sub Delay(ByRef As Double=1)
. . . .
. . . .
Sub Delay(ByRef seconds As Double)
. . . .
. . . .
End Sub
counting_pine
Site Admin
Posts: 6323
Joined: Jul 05, 2005 17:32
Location: Manchester, Lancs

Post by counting_pine »

The default value should go in the Declare. If the intended default value doesn't appear in code before you call the function, then FB won't think it has a default value, and will require the parameter.

In the Declare, you should keep the byref/byval as well, but the parameter name can be omitted. E.g. "declare sub delay(byref as double = 1)"

I would advise putting the default value only in the Declare if you have one, so it's only in one place in the code. I don't know what will happen if you have different default values in the Declare and the header.

PS. Does the parameter need to be Byref? "Delay" doesn't sound like the kind of sub that modifies its parameter. If you're not changing it, Byval would be better here.
fxm
Moderator
Posts: 12081
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Post by fxm »

I totally agree.
Remark : for the default value in case of conflict, Declare seems to have priority over header.
mccp1999
Posts: 24
Joined: Jul 03, 2006 23:59
Location: West Sussex

Thanks

Post by mccp1999 »

Thanks alot guys for the help.

Sorry Ive not got back sooner

I understand the points raised, especially having things in one place and the byref and byval

Thanks again
Post Reply