Android Question Question About Select Case Variable

Scantech

Well-Known Member
Licensed User
Longtime User
B4X:
    Dim x As Int = 2
    Select Case x
        Case 1
            Dim WhatString As String
            WhatString = "Hello"
        Case 2
            WhatString = "Hi"
            Log(":" & WhatString)
    End Select

This does not cause any errors. When compiled is the WhatString declared for Case 2? i spotted this in my codes without warning.
 
Last edited:

emexes

Expert
Licensed User
When compiled is the WhatString declared for Case 2?
Yes.

The B4A output Java code has:
B4X:
String _whatstring = "";
at the top of the Sub, ie WhatString is declared and initialized first-up regardless of what happens below, which for Case 1 is:
B4X:
//BA.debugLineNum = 72;BA.debugLine="Dim WhatString As String";
_whatstring = "";
//BA.debugLineNum = 73;BA.debugLine="WhatString = \"Hello\"";
_whatstring = "Hello";
and for Case 2 is:
B4X:
//BA.debugLineNum = 75;BA.debugLine="WhatString = \"Hi\"";
_whatstring = "Hi";
 
Upvote 0

Computersmith64

Well-Known Member
Licensed User
Longtime User
Yes.

The B4A output Java code has:
B4X:
String _whatstring = "";
at the top of the Sub, ie WhatString is declared and initialized first-up regardless of what happens below, which for Case 1 is:
B4X:
//BA.debugLineNum = 72;BA.debugLine="Dim WhatString As String";
_whatstring = "";
//BA.debugLineNum = 73;BA.debugLine="WhatString = \"Hello\"";
_whatstring = "Hello";
and for Case 2 is:
B4X:
//BA.debugLineNum = 75;BA.debugLine="WhatString = \"Hi\"";
_whatstring = "Hi";
Wow - I'd call that a bug. Logically that should cause an undeclared variable error .

- Colin.
 
Upvote 0

emexes

Expert
Licensed User
It's almost like B4a is trying to do what you wanted to do, rather than what you actually told it to do. Bear in mind that there is no standard constraining the design of BASIC dialects, and I am quite happy that B4A defaults to the BASIC tradition of taking reasonable default actions rather than unnecessary bombouts

Mind you, there's stuff I'm not so keen on too, compared to the way traditional BASICs do stuff, but generally those are the result of B4A being built upon Java.
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
It's a scope thing! B4X only has two scopes, global and local. All variables within a Sub, wherever they are declared, are local and visible to all code within the Sub. This is unlike Java, C++ or C#, for example, where variables can have block scoping within inner code blocks.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
The code you posted is valid.

This code is invalid:
SS-2019-04-04_14.53.25.png


You cannot declare the same variable with different types.
 
Upvote 0
Top