Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if a Variable is nil?

A common condition that all programs should do is to check if variables are assigned or not.

Take the below statements:

(1)

if Assigned(Ptr) then begin   // do something end; 

(2)

if Ptr <> nil then begin   // do something end; 

What is the difference between Assigned(Ptr) and Ptr <> nil?

like image 345
MajidTaheri Avatar asked May 15 '12 13:05

MajidTaheri


People also ask

How do you check if a variable is blank?

if ($var === null){ } // This checks if the variable, by type, IS null.

How do you know if a variable is empty or null?

To check for null variables, you can use a strict equality operator ( === ) to compare the variable with null . This is demonstrated below, where the boolean expression evaluates to true for only for null and evaluates to false for other falsy values.

Is null == undefined?

It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.

How do you check for null?

Use "==" to check a variable's value. A "==" is used to check that the two values on either side are equal. If you set a variable to null with "=" then checking that the variable is equal to null would return true.


2 Answers

It's usually the same... except when you check a function...

function mfi: TObject; begin   Result := nil; end;  procedure TForm1.btn1Click(Sender: TObject); type   TMyFunction = function: TObject of object; var   f: TMyFunction; begin   f := mfi;    if Assigned(f) then   begin     ShowMessage('yes'); // TRUE   end   else   begin     ShowMessage('no');   end;    if f <> nil then   begin     ShowMessage('yes');   end   else   begin     ShowMessage('no');  // FALSE   end; end; 

With the second syntax, it will check the result of the function, not the function itself...

like image 103
Whiler Avatar answered Sep 19 '22 04:09

Whiler


As far as performance, there is no difference. I personally prefer the second form as I find that humans can parse the meaning quicker.

like image 45
500 - Internal Server Error Avatar answered Sep 22 '22 04:09

500 - Internal Server Error