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
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.