B4J Question Are variables automatically initialized?

Alessandra Pellegri

Active Member
Licensed User
Longtime User
If I do:
Dim a as int
May I be sure that a is zero ?

And if i do:
type myType( a as int )

dim x as myType

x.a is always zero?

Thank you
 

Daestrum

Expert
Licensed User
Longtime User
The 'a' in the dim statement is not the same as the 'a' in the type statement.

If the dim and type statements are in Process_Globals then

The type statement creates a java class containing the field named 'a' which is only guaranteed to be 0 after the initialize method is called.

B4X:
  public static class _mytype
  {
    public boolean IsInitialized;
    public int a;
  
    public void Initialize()
    {
      this.IsInitialized = true;
      this.a = 0;
    }

The dim statement creates a java variable called '_a' which is set to 0.
B4X:
  public static int _a = 0;
 
Upvote 0

MarkusR

Well-Known Member
Licensed User
Longtime User
erel wrote only b4r did not initialized primitive datatype variables.
its also special that u not need to initialize a Type, its automatical.
 
Upvote 0

Alessandra Pellegri

Active Member
Licensed User
Longtime User
Thank you guys.

In effect looking at myType.initialize tip: it says that it put all variables to their default value. So for structures isn't automatic, I have to initialize.
 
Upvote 0

MarkusR

Well-Known Member
Licensed User
Longtime User
from generated source code i would agree that u need to use .initialize for a structur class.
but for any reason the integer inside have 0 as default value without the usage of initialize.
 
Upvote 0

Alessandra Pellegri

Active Member
Licensed User
Longtime User
from generated source code i would agree that u need to use .initialize for a structur class.
but for any reason the integer inside have 0 as default value without the usage of initialize.

I think that the reason is that when you turn on the PC, all registers are zeros. So if a dram cell isn't still used until that moment, the related variable is zero. But you cannot be sure.
 
Upvote 0
Top