Initialization to "nothing"

Q: How can you initialize something to ' '? I am reading Programming Principles and Practice Using C++ and many people say this is nonsense.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  // convert from inches to centimeters or centimeters to inches
// a suffix ā€˜iā€™ or ā€˜cā€™ indicates the unit of the input
// any other suffix is an error
int main()
{
constexpr double cm_per_inch = 2.54; // number of centimeters in
// an inch
double length = 1; // length in inches or
// centimeters
char unit = ' '; // a space is not a unit
cout<< "Please enter a length followed by a unit (c or i):\n";
cin >> length >> unit;
if (unit == 'i')
cout << length << "in == " << cm_per_inch*length << "cm\n";
else if (unit == 'c')
cout << length << "cm == " << length/cm_per_inch << "in\n";
else
cout << "Sorry, I don't know a unit called '" << unit << "'\n";
}
How can you initialize something to ' '?

You can do it like you do it on line 10.
Couldn't I just set the value to anything? Is ' ' the only option here?
char unit;
Last edited on
You never use the variable before passing it to cin>> so you don't need to initialize the variable at all if you don't want to.
It is possible for line 12 to fail to extract anything from the input stream. If that is the case, it makes sense that you want unit to be a predictable value and not accidentally one that you were expecting.

Of course, I guess you could just make sure the extraction happened and not worry about the initial value of unit.
If you use C++11 or later the value is never unpredictable. The new behaviour when it fails to extract anything is to set the variable to zero.

http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
If you use C++11 or later the value is never unpredictable. The new behaviour when it fails to extract anything is to set the variable to zero.
unit is of type char, so that doesn't apply.
Topic archived. No new replies allowed.