Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the conditional operator evaluate all arguments?

When writing this:

1: inline double f( double arg ) {
2:    return arg == 0.0 ? 0.0 : 1./arg;
3: }
4: const double d = f( 0.0 );

The microsoft visual studio 2005 64-bit compiler came with

line 4: warning C4723: potential divide by 0

While you and I can clearly see that a div-by-zero is never going to happen...

Or is it?

like image 371
xtofl Avatar asked Nov 24 '09 08:11

xtofl


2 Answers

The compiler is not able to statically analyze all code paths and take into account all possibilities all the time. Theoretically, complete analysis of a program behavior just by looking into its source code can provide a solution to halting problem, which is undecidable. Compilers have a limited set of static analysis rules to detect rules. The C++ standard does not require the compiler to issue such kind of warnings, so, no. It's not a bug. It's more like a nonexistent feature.

like image 59
mmx Avatar answered Oct 17 '22 05:10

mmx


No, the conditional operator does not evaluate both arguments. However, a potential divide-by-zero, if a compiler can detect such a thing, is typically reported. It is not for nought that the standard takes up ~2 pages to describe the behavior of this operator.

From N-4411:

5.16 Conditional operator

1 Conditional expressions group right-to-left. The first expression is contextually converted to bool (Clause 4). It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third expressions is evaluated. Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression.

Also, note:

3 Otherwise, if the second and third operand have different types, and either has (possibly cv-qualified) class type, an attempt is made to convert each of those operands to the type of the other.

The example you have cited has the same type for both the second and the third expressions -- rest assured, only the first will be evaluated.

like image 20
dirkgently Avatar answered Oct 17 '22 05:10

dirkgently