* * *

Author Topic: Assigned() Issues  (Read 645 times)

speleomania

  • New member
  • *
  • Posts: 8
Assigned() Issues
« on: February 09, 2017, 07:36:33 pm »
Can anyone confirm/comment on this?

Program AccessViolation;

var
  c: TSomeClass;

begin
  if Assigned(c) then ShowMessage(c.name); // Access violation
end;

The problem I'm having is that for some reason Assigned seems to always return True unless I manually do

begin
  c := nil;
  if Assigned(c) then ShowMessage(c.name); // This works
end;

I wasn't expecting having to manually initialise my object vars...is this normal?
 

howardpc

  • Hero Member
  • *****
  • Posts: 2111
Re: Assigned() Issues
« Reply #1 on: February 09, 2017, 07:48:05 pm »
I can't reproduce your issue. The following displays False, as one would expect:
Code: Pascal  [Select]
  1. program Project1;
  2.  
  3. {$Mode delphi}{$H+}
  4.  
  5. var
  6.   obj: TObject;
  7.  
  8. begin
  9.   WriteLn('Value of ''Assigned(obj)'' is ',Assigned(obj));
  10. end.

wp

  • Hero Member
  • *****
  • Posts: 3436
Re: Assigned() Issues
« Reply #2 on: February 09, 2017, 08:47:58 pm »
Some for me. But I would never rely on a variable being initialized automatically. Even if there seem to be rules (https://stackoverflow.com/questions/132725/are-delphi-variables-initialized-with-a-value-by-default), but I usually forget them (except that class members are always set to zero). Instead, it is easier to remember this more general rule:

Code: Pascal  [Select]
  1. program Project1;
  2.      
  3. {$Mode delphi}{$H+}
  4.      
  5. var
  6.   obj: TObject = nil;    // <--- initialization
  7.      
  8. begin
  9.   WriteLn('Value of ''Assigned(obj)'' is ',Assigned(obj));
  10. end.
Lazarus trunk / fpc 3.0.0 / Win32

howardpc

  • Hero Member
  • *****
  • Posts: 2111
Re: Assigned() Issues
« Reply #3 on: February 09, 2017, 09:18:22 pm »
Surely you can rely on documented compiler initializations, such as all globals being set to zero/nil and all class fields/variables set likewise; and strings and dynamic arrays always having an initial zero length?
Not that it hurts to make the initial value explicit, as in your example (however, perhaps in some cases, the nil value is then actually assigned twice).

speleomania

  • New member
  • *
  • Posts: 8
Re: Assigned() Issues
« Reply #4 on: February 09, 2017, 10:52:22 pm »
My bad!

I'm ashamed to admit I completely forgot about a class variable with the same name which messed me up. You guys are correct and free pascal is not at fault here

Case closed!

 

Recent

Get Lazarus at SourceForge.net. Fast, secure and Free Open Source software downloads Open Hub project report for Lazarus