[fpc-devel] Are global variables guaranteed to be zero?

Mark Morgan Lloyd markMLl.fpc-devel at telemetry.co.uk
Thu Jan 24 19:59:47 CET 2013


Apologies for revisiting an old thread.

michael.vancanneyt at wisa.be wrote:

>>>>>> Will global variables and static global arrays be always 
>>>>>> initialized to
>>>>>> zero?
>>>>>
>>>>> Yes.

>> Are there cases where locals are set to a sane initial state, e.g. for 
>> strings and dynamic arrays? What about (references to) objects?
> 
> Managed types are normally initialized. That means Ansistrings,
> UnicodeString, and COM interfaces and dynamic arrays (maybe I forget some)
> 
> Classes and objects are not. I am not sure about widestrings on Windows.

Looking at this code:

function WagnerFischerBestMatch(const pattern: string; stringList: 
TStringList): integer;

var	scratch: StringArray;	// array of string;
	i: integer;

begin
   for i := 0 to stringList.Count - 1 do
     scratch += stringList[i];

where + has been defined to append an element to the array, I get a 
warning that scratch hasn't been initialised. Similarly

function singleRadioGroup(items: TMenuItem): string;

var     i: integer;
         gi: integer= 0;
         name, firstName, checkedName: string;

begin
..
         if firstName = '' then

In view of what you said about managed types, is it safe to assume that 
the error message is spurious? I'm a little reluctant to add an explicit 
e.g. SetLength(scratch, 0) or to break the string declarations onto 
separate lines simply to suppress a warning, when it isn't necessary for 
correctness.

I note the fairly recent introduction of {%H- } to tell Lazarus to 
filter out specific warnings.

-- 
Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk

[Opinions above are the author's, not those of his employers or colleagues]



More information about the fpc-devel mailing list