Recent

Author Topic: Variable initialization  (Read 4289 times)

silvercoder70

  • Full Member
  • ***
  • Posts: 200
    • Tim Coates
Re: Variable initialization
« Reply #15 on: February 26, 2025, 11:13:29 pm »
 I grew up in a time when variables were not expected to be initialized by default... developers were responsible for explicitly assigning initial values. This approach ensured that programmers remained mindful of variable states AND avoided unintended behavior caused by hidden initializations or assomptions made. The lack of automatic initialization also means default *assignments* were avoided.

Having some sort of implicit defaults also makes assumptions about the compiler.


🔥 Pascal Isn’t Dead -> See What It Can Do: @silvercoder70 on YouTube

egsuh

  • Hero Member
  • *****
  • Posts: 1752
Re: Variable initialization
« Reply #16 on: February 27, 2025, 05:25:32 am »
You can assign default/initial values to global variables, but not within object.
In order to initialize values, you have to do that wtihin constructor. Old turbopascal had Init procedure for "object", I remember.

Code: Pascal  [Select][+][-]
  1. unit unit1;
  2.  
  3. interface
  4.     TMyObject = class
  5.        Boolean1: Boolean;
  6.  
  7.        constructor Create;
  8.    end;
  9.  
  10. var
  11.    Boolean2: Boolean = true;
  12.  
  13. implementation
  14.  
  15. constructor  TMyObject.Create;
  16. begin
  17.      Boolean1 := true;
  18. end;
  19.  
  20. end.
  21.  

This is the most basic principle AFAIK.

Khrys

  • Sr. Member
  • ****
  • Posts: 400
Re: Variable initialization
« Reply #17 on: February 27, 2025, 09:39:46 am »
You can rely on class member variables to be zero-initialized. Quoting the reference guide:

Quote
Calling the constructor will provoke a call to the virtual class method NewInstance, which, in its default implementation, calls GetMem, to allocate enough space to hold the class instance data, and then zeroes out the memory.

This means that booleans will be  False,  integers and floats will be 0, strings will be '', dynamic arrays will have length 0 and pointers / class instances will be  Nil  -  just because these values all happen to be represented by an all-zero bit pattern.

Code: Pascal  [Select][+][-]
  1. type
  2.   TPerson = class
  3.     Name: String;
  4.     Married: Boolean;
  5.   end;
  6.  
  7. procedure Test()
  8. var
  9.   Baby: TPerson;
  10. begin
  11.   Baby := TPerson.Create(); // Before this assignment, the pointer value of Baby itself is undefined and its instance data doesn't exist yet
  12.   Assert((Baby.Name = '') and (Baby.Married = False), 'Someone must have overridden NewInstance');
  13. end.



Global variables are also zero-initialized, again quoting the reference guide:

Quote
By default, simple variables in Pascal are not initialized after their declaration. Any assumption that they contain 0 or any other default value is erroneous: They can contain rubbish. To remedy this, the concept of initialized variables exists. The difference with normal variables is that their declaration includes an initial value, as can be seen in the diagram in the previous section.

Remark 2 exceptions to this rule exist:

  • Managed types are an exception to this rule: Managed types are always initialized with a default value: in general this means setting the reference count to zero, or setting the pointer value of the type to Nil. See section 3.9, page 226
  • Global variables are initialized with the equivalent of zero.

MarkMLl

  • Hero Member
  • *****
  • Posts: 8550
Re: Variable initialization
« Reply #18 on: February 27, 2025, 10:09:22 am »
You can rely on class member variables to be zero-initialized. Quoting the reference guide:

Read that link again: that is the /default/ case, and can be overridden e.g. https://www.mail-archive.com/fpc-pascal@lists.freepascal.org/msg57144.html

Note that this is the /general/ part of the forum, and we should not be making too many assumptions about what elements of the FCL, LCL etc. have been pulled in.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

fxeconomist

  • Jr. Member
  • **
  • Posts: 67
Re: Variable initialization
« Reply #19 on: February 27, 2025, 04:16:47 pm »
That is not a 'normal' variable declaration rather a field inside an object/class.

With the normal kvetching about the distinction between an object and an instantiated class :-(

Detail at https://github.com/zsoltszakaly/OOPstructuresinpascal

MarkMLl

I couldn't get any download link for that openoffice file.

MarkMLl

  • Hero Member
  • *****
  • Posts: 8550
Re: Variable initialization
« Reply #20 on: February 27, 2025, 04:39:33 pm »
I couldn't get any download link for that openoffice file.

??? Go to the link, you'll see a .odt file. Download it using your browser, open it.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

fxeconomist

  • Jr. Member
  • **
  • Posts: 67
Re: Variable initialization
« Reply #21 on: February 27, 2025, 05:08:02 pm »
Alright, then it was my Linux browser at fault then.
I do use Linux for browsing on my main Windows.

fxeconomist

  • Jr. Member
  • **
  • Posts: 67
Re: Variable initialization
« Reply #22 on: February 27, 2025, 05:24:44 pm »
I grew up in a time when variables were not expected to be initialized by default... developers were responsible for explicitly assigning initial values. This approach ensured that programmers remained mindful of variable states AND avoided unintended behavior caused by hidden initializations or assomptions made. The lack of automatic initialization also means default *assignments* were avoided.

Having some sort of implicit defaults also makes assumptions about the compiler.

I did grow up at that time as well. It didn't piss me off, but those were simple programmes I was writing at that time. But, in complex OOP systems, it's a must.
An object is like a car. It has to be error-free at the moment the object is ready for use. You can't just turn the key and have it explode. It shouldn't need extra care, like extra global initialization flags with combined constructor calls, written in a such a way to make sure the constructor doesn't wipe it clean on a subsequent call... Hence the name, "constructor".
It's a not a "reset", it's a "constructor", it's a one-and-done thing. It shouldn't even be called more than once, and if is, it should be bypassing the execution on a subsequent call.

MarkMLl

  • Hero Member
  • *****
  • Posts: 8550
Re: Variable initialization
« Reply #23 on: February 27, 2025, 05:32:09 pm »
An object ... shouldn't need extra care, like extra global initialization flags with combined constructor calls, written in a such a way to make sure the constructor doesn't wipe it clean on a subsequent call... Hence the name, "constructor".

It's a not a "reset", it's a "constructor", it's a one-and-done thing. It shouldn't even be called more than once, and if is, it should be bypassing the execution on a subsequent call.

...And that's why the constructor is applied to a type returning an instance, not to an existing instance. If it /can/ be applied to an instance, then something's wrong.

But as I've already said, be very careful with terminology here. Objects (as introduced by Turbo Pascal) are dead, and the FPC team has made it quite clear that they'll get absolutely minimal maintenance.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

ASerge

  • Hero Member
  • *****
  • Posts: 2477
Re: Variable initialization
« Reply #24 on: February 27, 2025, 07:33:30 pm »
This way every method can first call TrueConstructor to have some defaults loaded, while every subsequent call will leave the object untouched.
In this case, it is possible because initialization is guaranteed for managed types (Initialized):
Code: Pascal  [Select][+][-]
  1. {$MODE OBJFPC}
  2. {$IFDEF WINDOWS}
  3.   {$APPTYPE CONSOLE}
  4. {$ENDIF}
  5.  
  6. type
  7.   TSomething = object
  8.     Initialized: array of Boolean;
  9.     SomeData: Integer;
  10.     constructor Init;
  11.   end;
  12.  
  13. constructor TSomething.Init;
  14. begin
  15.   if Initialized = nil then
  16.   begin
  17.     SomeData := 3;
  18.     SetLength(Initialized, 1);
  19.   end;
  20. end;
  21.  
  22. var
  23.   R: TSomething;
  24. begin
  25.   R.Init;
  26.   Writeln(R.SomeData);
  27.   Readln;
  28. end.

silvercoder70

  • Full Member
  • ***
  • Posts: 200
    • Tim Coates
Re: Variable initialization
« Reply #25 on: February 27, 2025, 10:43:58 pm »
using the car analogy...

if you create the first car:

car1 := TCar.Create(...)

you will get an instance of a car. Great! But then...

"It shouldn't even be called more than once, and if is, it should be bypassing the execution on a subsequent call"

what happens if the car is inserted into a list where the list comes the owner of the car? (That on freeing the list the cars get destroyed.) How can I create a second car to add?
🔥 Pascal Isn’t Dead -> See What It Can Do: @silvercoder70 on YouTube

dbannon

  • Hero Member
  • *****
  • Posts: 3725
    • tomboy-ng, a rewrite of the classic Tomboy
Re: Variable initialization
« Reply #26 on: February 28, 2025, 04:48:18 am »

Where is this thread going ?

As I understand it, global variables are initialized as zero (or false, or nil). Khrys showed us where in the docs this is declared. So, the 'real globals' that Mark frowns upon, the public variable in an instance of a class, even the private variable in a class are all initialized when an instance is made. 

Local variables are not so initialized, so, if you want them initialized, do so when declaring them.

fxeconomist, if your booleans are class data, yes, they will be initialized as false. If they are local variables, in a function or procedure, just do -

Code: Pascal  [Select][+][-]
  1. var MyBool : boolean = false;

Destroying cars ??  Wot ?  How about simple answers to simple questions  please ?

Davo



Lazarus 3, Linux (and reluctantly Win10/11, OSX Monterey)
My Project - https://github.com/tomboy-notes/tomboy-ng and my github - https://github.com/davidbannon

440bx

  • Hero Member
  • *****
  • Posts: 6137
Re: Variable initialization
« Reply #27 on: February 28, 2025, 07:00:36 am »
Personally, I believe that, in all cases, if a programmer wishes to depend on a variable having a particular initial value then the programmer should initialize the variable to that value.

A plausible exception is if the variable is global because most compilers today will place the variable in an initialized data section (usually binary zeroes) but, it is still poor programming to rely on that, after all, maybe the correct/useful value(s) isn't binary zeroes.

Conclusion: you're the programmer: you want a variable/structure to have a particular value ? simple: explicitly set it to that value.  It is nothing other than good programming.


FPC v3.2.2 and Lazarus v4.0rc3 on Windows 7 SP1 64bit.

silvercoder70

  • Full Member
  • ***
  • Posts: 200
    • Tim Coates
Re: Variable initialization
« Reply #28 on: February 28, 2025, 12:08:58 pm »

Destroying cars ??  Wot ?  How about simple answers to simple questions  please ?

Davo

In this post - https://forum.lazarus.freepascal.org/index.php/topic,70370.msg548489.html#msg548489  ...

Quote
An object is like a car. It has to be error-free at the moment the object is ready for use. You can't just turn the key and have it explode. It shouldn't need extra care, like extra global initialization flags with combined constructor calls, written in a such a way to make sure the constructor doesn't wipe it clean on a subsequent call... Hence the name, "constructor".
It's a not a "reset", it's a "constructor", it's a one-and-done thing. It shouldn't even be called more than once, and if is, it should be bypassing the execution on a subsequent call.

This is why I used that example of the "car". The last sentence seems to indicates you cannot do this:

Code: Pascal  [Select][+][-]
  1. c := TSomeObject.Create();  // First creation
  2. c := TSomeObject.Create();  // Second creation without freeing the first
  3.  

So here is a real (world) example:

Code: Pascal  [Select][+][-]
  1.       while not Query.EOF do
  2.       begin
  3.         Extension := TExtension.Create;
  4.         Extension.ID := Query.FieldByName('ID').AsInteger;
  5.         Extension.Name := Query.FieldByName('Name').AsString;
  6.         Extension.Voicemail := Query.FieldByName('Voicemail').AsString;
  7.         ...
  8.         {Add to our list - ownership transferred to the list}
  9.         ExtensionList.Add(Extension);
  10.        
  11.         Query.Next;
  12.       end;
  13.  

How is this any different?! the contructor is called twice?

🔥 Pascal Isn’t Dead -> See What It Can Do: @silvercoder70 on YouTube

MarkMLl

  • Hero Member
  • *****
  • Posts: 8550
Re: Variable initialization
« Reply #29 on: February 28, 2025, 12:14:05 pm »
Code: Pascal  [Select][+][-]
  1. c := TSomeObject.Create();  // First creation
  2. c := TSomeObject.Create();  // Second creation without freeing the first
  3.  

Stretching the metaphor: the family car was stolen and you're replacing it with another which fills the same role.

It is /not/ the same car, and the fact that it's stored in the same garage is irrelevant.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

 

TinyPortal © 2005-2018