c++ - Explain the following output? -
please explain output:
#include<iostream.h> int main() { int i= -3, j=2, k=0, m; m = ++i || ++j && ++k; cout<< <<" " << j << " " << k <<" "<<m; homecoming 0; }
output : -2 2 0 1
here's thought: (++i || ++j) && (++k) //considering precedence order ++i becomes -2 first part of or true, won't check 2nd part. (thanks joachim pileborg telling me short circuit evaluation)
so overall, first part of , true. not plenty statement true, 2nd part must true to. ++k makes k = 1 here's wrong. why k not increasing?
whereas, in case:
#include<iostream.h> int main() { int i= -1, j=2, k=0, m; m = ++i || ++j && ++k; cout<< <<" " << j << " " << k <<" "<<m; homecoming 0; }
output: 0 3 1 1
i got 1 considering short circuit evaluation.
let's start code snippet
#include<iostream.h> int main() { int i= -3, j=2, k=0, m; m = ++i || ++j && ++k; cout<< <<" " << j << " " << k <<" "<<m; homecoming 0; }
it obvious m
have boolean value converted int. ++i
equal -2 unequal 0 other expressions not evaluated because known whole look equal true
. after statement
m = ++i || ++j && ++k;
m
equal 1 , i
equal -2 other variables not changed.
in code snippet
#include<iostream.h> int main() { int i= -1, j=2, k=0, m; m = ++i || ++j && ++k; cout<< <<" " << j << " " << k <<" "<<m; homecoming 0; }
++i
equal 0. right operand of operator ||
evaluated. operand is
++j && ++k
as ++j
equal 3 , not equal 0 ++k
evaluated , equal 1. both operands of operator &&
not equal 0 result equal true
thus == 0, j == 3, k == 1, m == 1.
from c++ standard
5.14 logical , operator
1 && operator groups left-to-right. operands both contextually converted bool (clause 4). result true if both operands true , false otherwise. unlike &, && guarantees left-to-right evaluation: sec operand not evaluated if first operand false.
5.15 logical or operator
1 || operator groups left-to-right. operands both contextually converted bool (clause 4). returns true if either of operands true, , false otherwise. unlike |, || guarantees left-to-right evaluation; moreover, sec operand not evaluated if first operand evaluates true.
c++ operator-precedence
No comments:
Post a Comment