Difference between revisions of "Brackets around procedure parameters"

From HashVB
Jump to: navigation, search
(When to use ()...)
 
(Rearranged things a bit)
 
(4 intermediate revisions by 3 users not shown)
Line 10: Line 10:
  
 
This will fail with a "Syntax Error" as "Parameter1, Parameter2" can not be evaluated to a single value.
 
This will fail with a "Syntax Error" as "Parameter1, Parameter2" can not be evaluated to a single value.
 +
 +
If you want to use those brackets but not make use of the return value, then you can make use of the Call keyword:
 +
 +
Call ProcedureName(Parameter1, Parameter2)
 +
 +
This syntax is equivalent to the other. Parameters are not evaluated, and the brackets are mandatory.
  
 
When calling subroutines or functions, you should ONLY ever use brackets around the parameters of procedure calls if you are making use of the return value (this includes the Call keyword) or around a single parameter if you want it to be evaluated first.
 
When calling subroutines or functions, you should ONLY ever use brackets around the parameters of procedure calls if you are making use of the return value (this includes the Call keyword) or around a single parameter if you want it to be evaluated first.

Latest revision as of 08:11, 14 September 2006

float
 This article is based on Visual Basic 6. Find other Visual Basic 6 articles.

There is a very common mistake when calling functions and procedures, to put brackets around all the parameters. This is often made worse by it "working" some of the time. Consider the following code:

ProcedureName (Parameter1)

Now, this will work most of the time, but it is not doing what you expect. As there is only one parameter, the brackets causes it to be evaluated first. This isn't a problem when passing a simple data type by value (byval), but when passing values that you expect to be changed (byref) or objects, it will fail. This is highlighted when you try and add a second parameter:

ProcedureName (Parameter1, Parameter2)

This will fail with a "Syntax Error" as "Parameter1, Parameter2" can not be evaluated to a single value.

If you want to use those brackets but not make use of the return value, then you can make use of the Call keyword:

Call ProcedureName(Parameter1, Parameter2)

This syntax is equivalent to the other. Parameters are not evaluated, and the brackets are mandatory.

When calling subroutines or functions, you should ONLY ever use brackets around the parameters of procedure calls if you are making use of the return value (this includes the Call keyword) or around a single parameter if you want it to be evaluated first.