Graal Forums

Graal Forums (https://forums.graalonline.com/forums/index.php)
-   New Scripting Engine (GS2) (https://forums.graalonline.com/forums/forumdisplay.php?f=153)
-   -   Ternary Operator question.. (https://forums.graalonline.com/forums/showthread.php?t=71632)

JkWhoSaysNi 01-23-2007 12:15 AM

Ternary Operator question..
 
Why doesn't this work:

variable ? function() : function2();

yet this does:

x = variable ? function() : function2();

The first example never gets processed. It's easier and neater than using

if (var) {
function();
}
else {
function2();
}

Tolnaftate2004 01-23-2007 01:09 AM

Quote:

Originally Posted by JkWhoSaysNi (Post 1267669)
variable ? function() : function2();

You've written it as if it were some sort of function. This is like doing
1+1;
It's just an operator.

Falcor 01-23-2007 01:21 AM

Quote:

Originally Posted by JkWhoSaysNi (Post 1267669)
Why doesn't this work:

variable ? function() : function2();

yet this does:

x = variable ? function() : function2();

The first example never gets processed. It's easier and neater than using

if (var) {
function();
}
else {
function2();
}

I recommend you don't use the ternary operator for anything aside from simple substitutions. eg... (x>1? 0 : 1)
Its a very bad programming practice to use it as flow-control. It's not intended for that.

JkWhoSaysNi 01-23-2007 01:33 AM

Why? It's only like a 2 line case statement.

It's much neater than either a case statement or if / else and has the same result.

Falcor 01-23-2007 01:52 AM

Quote:

Originally Posted by JkWhoSaysNi (Post 1267731)
Why? It's only like a 2 line case statement.

It's much neater than either a case statement or if / else and has the same result.

You sacrifice code clarity for a few less characters. if(condition) this; else that; makes more sense than (condition? this : that) when you glance at your code. You shouldn't have to comment code that documents itself either.

There is a reason why ?: is considered an operator and not flow control. Because it isn't.

In reference to your original question, the compiler probably skips over statements that don't make sense like 1+1; Why waste CPU resources on some stand alone expression whose computed value is never used? The assumption the compiler makes is that (?:) is used for expressions, not for program flow. To act otherwise is dangerous, especially if the nature of the compiler changes, it may break your code.

Admins 01-23-2007 03:29 PM

Hmmm The compiler was skipping the operation, although it should may be changed so that it is more compatible to C/C++.


All times are GMT +2. The time now is 05:03 AM.

Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2026, vBulletin Solutions Inc.
Copyright (C) 1998-2019 Toonslab All Rights Reserved.