0
Can someone explain how this program works?
6 Answers
+ 1
Nitin Bhattacharyya
the comma operator is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value. And in your samples code it evalute 1, then 2, then 3 and their result is discarded and then 4 condition d=0 is evaluated so after that condition no other conditions is present that's what it is resultant if condition which is 0 which make if condition false and else part is evaluated and printed
0
comma operator is a binary operator that evaluates the last member of the sequence (a,b,...,v), returns its value and performs the if condition check based on that value. eg.
int a = 0;
int b = 1;
if(a, b) {
// b is the last element
// b is evaluated (the value of b)
// returns 1
// 1 is equivalent to boolean true
// so the code here runs
}
if(b, a) {
// a = 0
// which is equivalent to false
// therefore this doesnt get
// executed
}
in your example, d is the last element and is equal to 0 which is equivalent to boolean false. so the condition becomes false and the code block doesn't get executed.
0
Abhi So after reading the answers I am understanding how the IF is working,now how are we assigning 0 to char d?? Wouldn't writing char d=0 means we are writing the ascii code?sorry for having too many doubts
0
Bilbo Baggins that's because your final condition is 0 so it is evaluate and give resultant so if(0) condition false and else part is evaluated
If you do (0,1) in if then if part will be evaluated
0
d='0' writes the ascii code
- 1
Comma operator is not an operator used to concatenate values. Simply does something but defers test to next expression.
Some result with "if (1,0)": if is not entered!