QB64.org Forum
Active Forums => QB64 Discussion => Topic started by: Richard on March 17, 2020, 06:09:40 am
-
Trying out sharing variables - what is wrong/missing with code below (c% not passed). If enable COMMON SHARED c% the program works correctly.
'COMMON SHARED c%
TYPE Cs
c AS INTEGER
END TYPE
DIM Cs AS Cs
c% = 2
PRINT "Main Module C% = ";: PRINT c%
MySUB
PRINT "Main Module C% = ";: PRINT c%
END
SUB MySUB ()
SHARED Cs AS Cs
PRINT "SUB TEST () C% = ";: PRINT c%
c% = -1
PRINT "SUB TEST () C% = ";: PRINT c%
END SUB
-
I suspect you may be a little confused, because the Cs variable is not being used at all in the program. For instance, here's an equivalent program to what you posted, with unused parts removed:
'COMMON SHARED c%
c% = 2
MySUB
c% = -1
The c% in the main program is entirely independent from the c% in MySUB, unless you uncomment the COMMON SHARED c% declaration at the top. Then references to c% in MySUB become references to c% in the main program.
On a side note, no need for "COMMON". "DIM SHARED c%" is considered (by me, anyway - don't take me too seriously) neater.
-
Thanks Luke for your reply.
Not that it really matters (as you have provided a "corrected" solution) …
Just for my interest, can you adjust my code to use the Type variable Cs as being the shared variable?
-
Sure.
Cs.c = 2
PRINT "Main Module: "; Cs.c
MySUB
PRINT "Main Module: "; Cs.c
PRINT "SUB TEST (): "; Cs.c
Cs.c = -1
PRINT "SUB TEST (): "; Cs.c
Now, I've fiddled a few other things because I'm strongly opinionated; others' tastes may be different:
- I renamed the User-Defined Type so it's different to the variable itself. I find it confusing when the same name is used in two different places.
- There is no "SHARED" line inside the sub, instead the Cs variable is DIM SHARED in the main program. I never use the SHARED-inside-a-sub technique because I get lost keeping track of everything.
- You can print multiple things by just separating them with ";", no need for another PRINT keyword :)
The main magic here is that you create a variable (Cs) with DIM SHARED, then that variable and all its fields can be used by all subs (and functions, of course).
-
Thankyou very much Luke.
Works exactly how I wanted it too (the print statements only used for diagnostic).
Now I understand much better how to apply the TYPE functionality, though in my simple example there is no benefit over your first answer.