Comma Operator in If Condition

comma operator in if condition

http://en.wikipedia.org/wiki/Comma_operator:

In the C and C++ programming languages, the comma operator
(represented by the token ,) is a binary operator that evaluates its
first operand and discards the result, and then evaluates the second
operand and returns this value (and type).

In your first if:

if (a, b)

a is evaluated first and discarded, b is evaluated second and returned as 0. So this condition is false.

In your second if:

if (b, a)

b is evaluated first and discarded, a is evaluated second and returned as 1. So this condition is true.

If there are more than two operands, the last expression will be returned.

If you want both conditions to be true, you should use the && operator:

if (a && b)

What is the advantage of commas in a conditional statement?

Changing your example slightly, suppose it was this

if ( a = f(5), b = f(6), ... , thisMustBeTrue(a, b) )

(note the = instead of ==). In this case the commas guarantee a left to right order of evaluation. In constrast, with this

if ( thisMustBeTrue(f(5), f(6)) )

you don't know if f(5) is called before or after f(6).

More formally, commas allow you to write a sequence of expressions (a,b,c) in the same way you can use ; to write a sequence of statements a; b; c;.
And just as a ; creates a sequence point (end of full expression) so too does a comma. Only sequence points govern the order of evaluation, see this post.

But of course, in this case, you'd actually write this

a = f(5);
b = f(6);
if ( thisMustBeTrue(a, b) )

So when is a comma separated sequence of expressions preferrable to a ; separated sequence of statements? Almost never I would say. Perhaps in a macro when you want the right-hand side replacement to be a single expression.

What does a comma mean inside an 'if' statement?

The programmer has used the comma operator to provide two unrelated expressions in a single statement. Because it's a single statement, both expressions are "inside" the if condition.

It's a poor hack, which would be better done with actual {} braces surrounding two statements.

Your example is not equivalent; it should be:

if (g[i][j] == 0) 
{
dfs(g, i, j);
++regions;
}

Using the comma operator in if statements

The expression used as an initializer expression must be an assignment-expression so if you want to use a comma operator you must parenthesize the initializer.

E.g. (not that what you are attempting makes much sense as 6 + 4 has no side effects and the value is discarded and i == 10 uses the uninitialized value of i in its own initializer.)

if (int i = (6 + 4, i == 10)) // behaviour is undefined

Did you really mean something like this?

int i = 6 + 4;
if (i == 10)

When using the form of if that declares a new variable the condition checked is always the value of the initialized variable converted to bool. If you want the condition to be an expression involving the new variable you must declare the variable before the if statement and use the expression that you want to test as the condition.

E.g.

int i;
if ((i = 6 + 4) == 10)

Why does javascript accept commas in if statements?

The comma operator chains multiple expressions together, and the result of the operation is the value of the last operand. The only real use for it is when you need multiple side effects to occur, such as assignment or function calls.

Can comma separated expressions be used as if statement in Javascript?

It's a series of statements really

popup_window != is_null // if true, continue to the statement in the parenthesis
&&
(
"function" == typeof popup_window.close // if true continue to close the window
&&
popup_window.close()
, popup_window = is_null // this is executed as long as "popup_window != is_null"
); // is truthy, it doesn't depend on the other conditions

assuming is_null is really null, firstly popup_window must not be null.

Secondly, we can assume popup_window is another window, opened with window.open, as it supposedly has to have a close function, and it's a bit of a Yoda condition, but it can also be written

typeof popup_window.close === "function"

so popup_window has to have a close method to continue to the next step.
The final step closes the popup window if it's not null, and if it has a close method.

popup_window.close()

so the other two conditions have to be truthy to get this far, there has to be a window, and it has to have a close method, and then that close method is called, and the window is closed.

And then there's the comma. From the docs

The comma operator evaluates each of its operands (from left to right)
and returns the value of the last operand.

and we have

("function" == typeof popup_window.close && popup_window.close(), popup_window = is_null);

lets write it a little differently

(                          // ↓ must be thruthy .... ↓ for this to execute
(typeof popup_window.close === "function" && popup_window.close())
, popup_window = is_null
); // ↑ unrelated, it's just another operand, seperated by comma

The trick here is that the last part, after the comma, is always executed, as all operands seperated by the comma is evaluated.

This means that if popup_window is not is_null, popup_window is explicitly set to is_null, regardless of the second condition.

The second condition is also only exectuted it popup_window is not is_null, it then checks if there is a close() method, and closes the window, the statement after the comma is unrelated to the outcome of that condition.

To write it even simpler (the way it should have been written IMO)

if ( popup_window != is_null ) {

if ( typeof popup_window.close === "function" ) {
popup_window.close();
}

popup_window = is_null;

}

Comma in an if statement

In JavaScript, whenever you put more than one expression inside a pair of brackets, they are evaluated as the last expression, like in the example below:

var a = (1, 2);
var b = a + 1; // b = 2 + 1 = 3

So, in your case, the interpreter executes the attribution n = "value" and then parses the if taking a == b as condition. It's the same as:

n = "value";
if (a == b) {
// ...
}

This article explains this behaviour.

EDIT

However, this does not limit n to the if's scope. This same thing happens to var declarations in for loops:

for (var i = 0; i < 10; i++) {
// Do stuff...
}
console.log(i); // Logs 10

EDIT 2

As Ethan Brown mentioned, is also good to tell about variable hoisting, which is basically the fact that, in JavaScript, values can be assigned to variables before declaring them. The following code shows this behaviour and was extracted from this MDN article:

bla = 2
var bla;

// The above code is valid, since
// it's implicitly understood as:

var bla;
bla = 2;

The same occurs with functions:

foo();
function foo() {
console.log('bar');
}

comma inside if statment in javascript

The comma operator in JavaScript is pretty similar to the concept in other C-like languages. It's a way of stringing multiple expressions together into one (syntactic) expression. The value of the whole thing is the value of the last expression in the list.

Thus in this case, container = $("#content") is evaluated, and then a is evaluated. The value of the whole thing is the value of a.

A good question is why that code was written that way. There are times when the comma operator is useful, but usually it's just a way to save some typing and make code a little more concise.

C++ for with multiple control statements using comma operator

This is how comma operator works. Its 1st operand x < 3 is evaluated, then the result is discarded; then the 2nd operand y < 4 is evaluated and the value is returned as the return value of the comma operator. x < 3 has not any effects here.

You might want to use operator&& or operator|| for this case, e.g. x < 3 && y < 4 or x < 3 || y < 4 based on your intent.



Related Topics



Leave a reply



Submit