Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm assuming that you will want to initialize a <em>global</em> variable, since for a local variable it just seems like a very awkward choice to forgo three lines of plain and understandable statements in order to have a constant of questionable value.</p> <p>At the global scope, we can't have errors in the initialization, so we'll have to handle them somehow. Here are some ideas.</p> <p>First, a templated little construction helper:</p> <pre><code>template &lt;typename T&gt; T cinitialize(std::istream &amp; is) noexcept { T x; return (is &amp;&amp; is &gt;&gt; x) ? x : T(); } int const X = cinitialize&lt;int&gt;(std::cin); </code></pre> <p>Note that global initializers must not throw exceptions (under pain of <code>std::terminate</code>), and that the input operation may fail. All told, it's probably pretty bad design to initialize global variables from user input in such a fashion. Perhaps a fatal error would be indicated:</p> <pre><code>template &lt;typename T&gt; T cinitialize(std::istream &amp; is) noexcept { T x; if (!(is &amp;&amp; is &gt;&gt; x)) { std::cerr &lt;&lt; "Fatal error while initializing constants from user input.\n"; std::exit(1); } return x; } </code></pre> <p>Just to clarify my position after some discussion in the comments: In a local scope I would <em>never</em> resort to such an awkward crutch. Since we're processing <em>external, user-supplied</em> data, we basically have to live with failure as part of the normal control flow:</p> <pre><code>void foo() { int x; if (!(std::cin &gt;&gt; x)) { /* deal with it */ } } </code></pre> <p>I leave it up to you to decide whether that's too much to write or too hard too read.</p>
 

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