Let us take these one by one:
Using the value of an uninitialized and unassigned scalar results in undefined behaviour. For example:
1 2 3
|
double a = 34.6 ;
double b ; // uninitialised
double c = a + b ; // undefined behaviour
|
In the original code,
regular_price and
fancy_price were not initialized at the point of their definition (line 15).
The switch
switch (type) assigned values to either one or the other, but not both. So one of them would remain uninitialised and unassigned, and
total_price=color_price+(area*paper_per_in)+(area*glass_per_in)+crown_price+regular_price+ fancy_price ;
engenders undefined behaviour.
NaN means
not a number; it represents an undefined or unrepresentable value.
https://en.wikipedia.org/wiki/NaN
A numeric operation with a NaN operand yields NaN. For instance,
5.78 + NaN == NaN
An uninitialised floating point value could be anything at all; it could hold some representation of NaN (there are a very large number of possible bit patterns that can represent NaN).
IEEE 754 NaNs are represented with the exponent field filled with ones (like infinity values), and some non-zero number in the significand (to make them distinct from infinity values); this representation allows the definition of multiple distinct NaN values, depending on which bits are set in the significand, but also on the value of the leading sign bit |
So it is not very surprising that using an uninitialised value in a floating point calculation yielded NaN.
To minimise the probability of mistakes of this kind,
postpone the definition of a local variable till we are close to the point of its first use; till we know how to initialize it.
http://stackoverflow.com/questions/6429460/should-one-keenly-consciously-attempt-to-postpone-variable-definitions-as-long