c - How is this constant expression evaluated? -


when explaining constant expressions, standard (well, draft n1570) gives thi "enlightening" example:

118)
thus, in following initialization,
static int = 2 || 1 / 0;
expression valid integer constant expression value one.

how expression evaluated?

the logical or, || returns either 0 or 1. first left operand evaluated, then, if evaluation of left operand resulted in 0, right operand evaluated , value of expression 0 if right operand evaluates 0, 1 otherwise. if evaluation of left operand resulted in nonzero value, entire expression evaluates 1 without evaluating right operand.

the precedence of division operator / higher precedence of logical or, expression

2 || 1 / 0 

is implicitly parenthesized

2 || (1 / 0) 

as expression-tree:

     (||)     /    \    2     (/)         /   \        1     0 

the precedence determines shape of tree, order of evaluation independent precedence (except insofar precedence determines data-dependencies). operators (||, &&, ?:, ,), order of evaluation of operands specified [and right operands of || , && aren't evaluated @ if result determined after evaluation of left operand, , of second , third operands of ?:, 1 evaluated - 1 determined evaluation of first operand], order of evaluation of children of operator-node unspecified.

since left operand of || in

static int = 2 || (1 / 0); 

(the constant expression 2) evaluates nonzero value, evaluation of expression stops there , value of

2 || 1 / 0 

is 1.

the evaluation of || specified in section 6.5.14, paragraph 4:

unlike bitwise | operator, || operator guarantees left-to-right evaluation; if second operand evaluated, there sequence point between evaluations of first , second operands. if first operand compares unequal 0, second operand not evaluated.

and return value ibid, paragraph 3:

the || operator shall yield 1 if either of operands compare unequal 0; otherwise, yields 0. result has type int.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -