I'm new at VB and I'm having a hard time doing something that should be very simple.
I'm trying to make an array of n+1 length and I keep getting "Constant expression required" when running the following code
Function binomial(n As Integer, p As Double) Dim probabilities(0 To n) As Double End Function
I understand that the arguments used to build the array must be constants, but do I create one from the argument of the function?
Thank you in advance
This error has the following causes and solutions: You tried to initialize a constant with a variable, an instance of a user-defined type, an object, or the return value of a function call.
A constant expression is an expression that contains only constants. A constant expression can be evaluated during compilation rather than at run time, and can be used in any place that a constant can occur.
The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions. In other examples (where the initializers are already compile-time constant expressions), declaring the variable as final may be what is needed.
Declare a dynamic array By declaring a dynamic array, you can size the array while the code is running. Use a Static, Dim, Private, or Public statement to declare an array, leaving the parentheses empty, as shown in the following example. Use the ReDim statement to declare an array implicitly within a procedure.
You can't DIM against a variable size. ReDim it instead
For example
Function binomial(n As Integer, p As Double) Dim probabilities() As Double ReDim probabilities(0 To n) MsgBox LBound(probabilities) MsgBox UBound(probabilities) End Function Sub test() Call binomial(3, 2) End Sub
Run the sub "test"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With