[Gambas-user] Question about writing If-clauses

Tobias Boege taboege at gmail.com
Thu Feb 1 08:43:12 CET 2018


On Thu, 01 Feb 2018, Rolf-Werner Eilert wrote:
> This is from the code snippet Benoit posted yesterday:
> 
> If InStr(Me.STRING_DELIM, Key.Text) And If hEditor.Column <
> hEditor.Current.Length Then
> 
> Do you always repeat "If" after "And", "Or" etc.? And why?
> 
> I know it (and write it) like If ... And ... Then
> 
> There is another line where it might make more sense:
> 
> If Not InsideStringEscape And If String.Mid$(hEditor.Current.Text,
> hEditor.Column + 1, 1) = Key.Text Then
> 
> I have to admit, it looks clearer like this, because it says "If Not ... And
> If [Yes] ... Then". But still I am surprised, would it be wrong to write it
> like
> 
> If Not ... And ... Then
> 
> Thanks for your insight!
> 

"If ... And ..." and "If ... And If ..." are different. You have to know
that "And If" is a distinct operator which does short-circuit evaluation
and the same holds for "Or If" [1].

In the above two specific instances, there is almost no difference between
And and And-If (except that And-If might be faster since it skips evaluating
the second condition if the first one is already false -- it's a smart AND
operator, so to speak), but consider code like this:

  If $hProcess And $hProcess.State = Process.Running Then $hProcess.Kill
  ' vs.
  If $hProcess And If $hProcess.State = Process.Running Then $hProcess.Kill

The first If will fail with a Null object error in the second condition
if $hProcess is Null, but the second will work.

Regards,
Tobi

[1] http://gambaswiki.org/wiki/lang/andif

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk


More information about the User mailing list