Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Does every if-else constructs can be replaced by an equivalent conditional expression using conditional operator?</p> </blockquote> <p>No, you've asked this backwards. <strong>The "bodies" of if/else contain statements, and it is not possible to turn every statement into an expression</strong>, such as try, while, break statements, as well as declarations. Many "statements" are really expressions in disguise, however:</p> <pre><code>++i; blah = 42; some_method(a,b,c); </code></pre> <p>All of these are statements which consist of one expression (increment, assignment, function-call, respectively) and could be turned into expressions within a conditional.</p> <p>So, let's reverse the question, since it sounds like you really want to know how equivalent if/else statements are to ternary conditional expressions: <strong>Can every conditional expression be replaced by equivalent if/else statements?</strong> Almost all, yes. A common example is return statements:</p> <pre><code>return cond ? t : f; // becomes: if (cond) return t; else return f; </code></pre> <p>But also other expressions:</p> <pre><code>n = (cond ? t : f); // becomes: if (cond) n = t; else n = f; </code></pre> <p>Which starts to point to where conditional expressions cannot be easily replaced: <strong>initializations</strong>. Since you can only initialize an object once, you must break up an initialization that uses a conditional into using an explicit temporary variable instead:</p> <pre><code>T obj (cond ? t : f); // becomes: SomeType temp; if (cond) temp = t; else temp = f; T obj (temp); </code></pre> <p>Notice this is much more tedious/cumbersome, and requires something type-dependent if SomeType cannot be default-constructed and assigned.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload