Results 1 to 2 of 2

Thread: Variants and Constants

  1. #1
    Guest

    Wink

    If I declare a constant like this:
    Code:
    Const NUM_EMPLOYEES As Integer = 4
    then Visual Basic uses a 2-byte integer to store my constant.

    If I instead declare the constant this way:
    Code:
    Const NUM_EMPLOYEES = 4
    will Visual Basic use a 16-byte Variant to store the constant????


  2. #2
    Frenzied Member
    Join Date
    Mar 2000
    Posts
    1,089
    constants aren't actually stored, The compiler simply replaces any references to that constant in your code to the value of that constant.


    so this

    Code:
    Const MYVAL = 46
    
    Public Sub Command1_Click
    
    Msgbox MYVAL
    
    Msgbox MYVAL + 4
    
    End Sub
    will compile exactly the same as


    Code:
    Public Sub Command1_Click
    
    Msgbox 46
    
    Msgbox 46 + 4
    
    End Sub
    The value is stored each time you use the constant as the same type as the function you are using the constant in expects.


    The reason you can set types for constants is to avoid overflows, for example


    Code:
    Const MYVAL = 250
    
    Public Sub Command1_Click
    
    Msgbox MYVAL * MYVAL
    
    End Sub
    will cause an overflow because the compiler interprets 250 as an integer (If you had typed Msgbox 250 * 250 you would still get an overflow)

    Code:
    Const MYVAL As Long = 250
    
    Public Sub Command1_Click
    
    Msgbox MYVAL * MYVAL
    
    End Sub

    will avoid this, it's the equivilant of
    Code:
    Public Sub Command1_Click
    
    Msgbox CLng(MYVAL) * CLng(MYVAL)
    
    End Sub
    but it desn't loose speed converting because it calculates CLng(250) at compile time.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width