Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TYPE and CONST within SUB/FUNCTION
#1
A while back I accidentally discovered that CONST can be used in SUBs and FUNCTIONs to create local constants. You can even use the same CONST variable name from the main code to create another unique local constant.

I was wondering if this worked with TYPEs. It appears it does not. While you can create a user defined TYPE within a SUB or FUNCTION it will always be seen globally. Is this correct behavior or should the user defined TYPE be local to the SUB and/or FUNCTION?

If the user defined TYPE is always to be seen globally then is it an oversight in the IDE to allow TYPEs to be created within a SUB or FUNCTION?

Code: (Select All)
OPTION _EXPLICIT

CONST SUB1_CONSTANT = 300 '      global everywhere unless also created within a subroutine
CONST SUB2_CONSTANT = 400

'TYPE Type_SUB1 '                if these lines are enabled an error occurs in SUB1()
'    a AS INTEGER
'    b AS INTEGER
'END TYPE

DIM Sub1_Variable AS Type_SUB1 ' Type_SUB1 is seen globally even though created in SUB1()
DIM Sub2_Variable AS Type_SUB2 ' Type_SUB2 is seen globally as well even though created in SUB2()

PRINT "-----------------"
PRINT "-- IN MAIN CODE -"
PRINT "-----------------"
PRINT "SUB1_CONSTANT  ="; SUB1_CONSTANT
PRINT "SUB2_CONSTANT  ="; SUB2_CONSTANT
PRINT
SUB1
SUB2

'----------------------------------------------------

SUB SUB1 ()

    CONST SUB1_CONSTANT = 100 '      constant is only local to this subroutine now

    TYPE Type_SUB1
        a AS INTEGER
        b AS INTEGER
    END TYPE

    DIM Sub1_Variable AS Type_SUB1 ' completely unique variable from one created at main code level

    PRINT "-----------------"
    PRINT "---- IN SUB1 ----"
    PRINT "-----------------"
    PRINT "SUB1_CONSTANT  ="; SUB1_CONSTANT
    PRINT "SUB2_CONSTANT  ="; SUB2_CONSTANT
    PRINT

END SUB

'----------------------------------------------------

SUB SUB2 ()

    CONST SUB2_CONSTANT = 200 '      constant is only local to this subroutine now

    TYPE Type_SUB2
        a AS INTEGER
        b AS INTEGER
    END TYPE

    DIM Sub2_Variable AS Type_SUB2 ' completely unique variable from one created at main code level

    PRINT "-----------------"
    PRINT "---- IN SUB2 ----"
    PRINT "-----------------"
    PRINT "SUB1_CONSTANT  ="; SUB1_CONSTANT
    PRINT "SUB2_CONSTANT  ="; SUB2_CONSTANT

END SUB
There are two ways to write error-free programs; only the third one works.
QB64 Tutorial
Reply


Messages In This Thread
TYPE and CONST within SUB/FUNCTION - by TerryRitchie - 07-09-2023, 07:57 PM
RE: TYPE and CONST within SUB/FUNCTION - by bplus - 07-10-2023, 12:30 AM
RE: TYPE and CONST within SUB/FUNCTION - by bplus - 07-10-2023, 12:55 AM
RE: TYPE and CONST within SUB/FUNCTION - by bplus - 07-11-2023, 01:22 AM



Users browsing this thread: 1 Guest(s)