Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Message: I've always written pretty structured code in other languages but I've also always had a problem doing so in VB. When I write a SELECT-CASE or IF-THEN-ELSE I'd like to use CALL to branch to the code to be executed. When I do this I lose whatever is calculated in variables. I know the problem has something to do with how the variables are defined. If anyone can shed some light on what I'm doing wrong I would appreciate it. I've never figured this out and my code is really hard to read without better structure.

Are you using VB6 or VB.Net because there is a huge difference in the way variables are passed.
In VB6 they are passed by reference by default which means that keeping the value is automatic unless you pass by value using By Val.
In VB.Net everything changed and variables are passed by value by default to bring it more into line with the C++ calling convention.
If you wish to retain the value and use any values calculated in the function, you need to pass the variable by reference and not leave it at the default by value. The Help files should tell you how to do that.
Stuart

Depends on how you are using the variables. If you are passing the variables as parameters in the CALL statement it makes no difference how the variables are declared.
However if you are using the same variables in the main code as well as the function then it will make a difference. However, PUBLIC variables should only be used if the variables is referenced from outside the module it is declared in, otherwise use DIM and pass them as a parameter.
Stuart

I'm not passing the variables with the CALL statements. I'm using CALL to branch.
I went back and changed the DIM statements to PUBLIC and was able to structure the program and have data passed in variables from one subroutine to another. I'm just wondering why you wouldn't want to do this? Passing with CALL seems to be more prevalent.

Using the PUBLIC declaration takes up more memory than just keeping the variables local. Once used PUBLIC variables remain in memory throughout the life of the module that uses them. Local variables are destroyed and the memory freed when the function is terminated. Passing variables with the CALL statement is more prevalent because it is the correct way of doing it.
When you get onto more complex programmes keeping variables Local as much as possible makes it far easier to debug and maintain and a lot easier for someone else to understand you code.
PUBLIC, as with GLOBAL variables, can get you into a terrible mess at times and should only be used when there is no other option.
Stuart

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |