On Tuesday, 7 April 2015 00:53:30 UTC+3, David Brown wrote:
> On 29/03/15 04:51, Öö Tiib wrote:
> > On Saturday, 28 March 2015 20:37:35 UTC+2, David Brown wrote:
> >> On 28/03/15 18:46, Bo Persson wrote:
> >>> On 2015-03-27 00:28, Stefan Ram wrote:
> >>>> I was reading a C++ book.
> >>>>
> >>>> It said:
> >>>>
> >>>> a variable should only be left uninitialized in extremely rare
> >>>> circumstances.
> >>>>
> >>>> ...
> >>>>
> >>>> char answer = 0; cin >> answer;
> >>>>
> >>>> What could be the reason for the » = 0« in such a case?
> >>>>
> >>>>
> >>>
> >>> What would be the reason for NOT initalizing the variable? Saving half a
> >>> nanosecond?
> >>>
> >>
> >> As a general point, you should not initialise a variable if you have
> >> nothing to put in it. That way you can make use of the compiler's
> >> static error checking to warn you if you accidentally use it later
> >> without having set it.
> >
> > Compilers do not typically warn if you pass uninitialied variable to
> > function by non-const reference or pointer.
>
> Just because compilers can't check /everything/, does not mean you
> should ignore the checks they /can/ do!
I don't suggest to ignore any opportunities. As next thing I
mentioned the tools (like valgrind and clang memory sanitizer)
that can do the runtime checks (when compiler can't detect
compile-time problem).
I was trying to say that leaving variables uninitialized is not
good *general* suggestion because the compile-time warnings are
situation-specific and tools that track such meta-information
run-time are platform-specific. Not *all* use those so not
*all* can gain from following of that advice. IOW it depends.
Other similar things are variables containing dangling pointers,
"moved from" variables and variables with contents from "dirty"
sources. We either use special tools that analyze usage of such
variables or use idioms that make it more likely that defects
manifest themselves without special tools instrumented.
> But I agree that sometimes using an "unavailable" or known-bad value is
> a good choice for initialisation when you don't have a real valid value.
I see the cons very well. My experiences show that the benefits
outweigh those on general case. Most of us like to fail ASAP
and use most terse syntax but C++ does not support us with that
choice.
Similarly assigning null to variable that contains dangling
pointer and does not leave scope anytime soon is widely accepted
idiom (and lot of coding standards require it) despite compilers
warn about potential (and tools detect actual) dangling pointer dereferencing / passing / returning / deleting. It is because the
code can use the null value in meaning of absence of value *and*
when it ignores it then null value manifests defects lot more
likely.