Question

Consider the code:

if(x = a/b, a%b) 
 printf("do this");
else 
 printf("do that");

Now if I replace if statement by if(x = a/b && a % b). Then it works also. So I want to know that replacing comma by && operator and vice-versa works always or not in if-else and loops

Was it helpful?

Solution

They are quite different!


In the first example, , is the comma operator, which 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).

So,

if(x = a/b, a%b) 

is equivalent to (thanks to @jaket)

x = a/b;
if(a%b) 

a%b will always be evaluated.


For the second one:

if(x = a/b && a % b)

is equivalent to

x = (a/b) && (a%b);
if( x )

a%b will only be evaluated if a/b (i.e. a/b is not zero) is true.

OTHER TIPS

if you replace the comma operator by &&, you're changing the logic slightly. What the comma operator does is it will execute x = a/b and "discard the result", i.e. it's not taken into consideration for the if's condition, only a%b is taken into account.

if you do

if(x = a/b && a % b)

then "do this" will be printed if and only if a/b is non zero and a % b is non zero. Whereas with the comma operator, "do this" is printed only if a % b is non zero.

if(x = a/b, a%b)

is an obfuscated, unreadable way of writing

x = a/b;
if(a%b)

But

x = a/b && a % b

is equivalent to

x = ( (a/b) && (a%b) );

To sum it up, don't mix a whole lot of different operators on the same line. The only thing you achieved with it was to confuse yourself, while creating bugs.

The && operator forces the the result of a/b as well into consideration in determining the expression x = a/b && a%b, In case of ,, the result of a/b is ignored. So replacing , with && will not work always. And not the right thing to do,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top