One line if/else - When did this happen?

I just did a test and this code compiles and runs properly:

if test then z = 1 else z = 2

I could swear I’ve tested "else on the same line" in the past and gotten an error. When was this implemented, and how did I not know about it?!?

(Geez, I’ve been using this environment since the 90’s and I’m still learning new things about it.)

That’s cool, it worked for me in the past for some time and then began to not work so I stopped using it. But I like that it’s working now…

Nothing new. From the docs:

Well, I’ll be… I just tried this in 2012r21 and it worked there too. I wonder when I tested this last?

Having said all this, I recommend against this syntax for all but the simplest statements. Using one line can make debugging harder. For example:

if expression1 = expression2 or expression3 > expression4 and expression1 <> expression3 then db.SQLExecute( sql1 ) else db.SQLExecute( sql2 )
// What just happened? Which one did it choose?

It was added when Mars wrote the new compiler. If Mars hadn’t left RS a while back, we’d now also have lambdas, which is the equivalent to Objective C’s “blocks” and other languages’ “closures”.

Now we have Joe, though, who isn’t far behind Mars on this. If there only weren’t all those Cocoa and Quicktime issues… :wink:

[quote=59233:@Kem Tekinay]I just did a test and this code compiles and runs properly:

if test then z = 1 else z = 2
[/quote]

Cool :slight_smile:

Don’t forget

#if TargetCocoa then MsgBox("Cocoa!")

Yes, but that won’t allow an else or #else on the same line.

Frankly, I’ve stopped writing one line If/Then clauses. It’s easier to debug and read if I use the full clause. And I don’t think there’s any overhead added by the extra lines. So if for some reason my If/then is never working, I can just put a break point at the conditional statement and see what’s going on or not going on…

Yeah, one-line ifs bother me to no end. While stepping over in the debugger, it is much less obvious what is going on.

[quote=59239:@Kem Tekinay]Well, I’ll be… I just tried this in 2012r21 and it worked there too. I wonder when I tested this last?

Having said all this, I recommend against this syntax for all but the simplest statements. Using one line can make debugging harder. For example:

if expression1 = expression2 or expression3 > expression4 and expression1 <> expression3 then db.SQLExecute( sql1 ) else db.SQLExecute( sql2 ) // What just happened? Which one did it choose? [/quote]

You need to put brackets around the comparisons to segregate which test(s) to be analyzed with each other.

For example…
if (expression1 = expression2 or expression3 > expression4) and expression1 <> expression3 then db.SQLExecute( sql1 ) else db.SQLExecute( sql2 )

It was just an example, but your post is a good argument against using this structure.

Here’s an example where one-line ifs make sense:

if value = 0 then break

No need to use 3 lines for that.