conversion

can someone explain what he means with this? (from a tutorial e-book), i tried and as i could figure out
nValue1
doesn't become
1.0
(and you can't change data type of a variable after it is declared?) if you print out
nValue1
it is still == 1.

1
2
3
4
5
// in the following expression the value of nValue1
// is converted into a double before performing the
// assignment
int nValue1 = 1;
nValue1 + 1.0;
Last edited on
(and you can't change data type of a variable after it is declared?)


That is correct. You declared 'nValue1' as an int... therefore it always is and always will be an int. There is no way to change it.

if you print out
nValue1
it is still == 1.


That is because you assign it to 1 on line 4... and you never change it:

1
2
3
4
5
6
7
8
9
int nValue = 1;  // <- nValue has 1 stored in it
nValue1 + 1.0;  // <- this does not change nValue... any more than "5 + 3" would change 5.
   // it merely takes whatever value is inside of nValue1, adds 1.0 to it... and in this case...
   //  throws it away.  Usually, such an addition would be assigned to something.
   //  so this makes more sense:

double v = nValue1 + 1.0; // <- here, we have the same thing.  nValue1's value of 1 is added
   // with 1.0, resulting in 2.0.  That 2.0 is then assigned to 'v'.
   //  note that this process does not change nValue1 -- it still contains 1. 




can someone explain what he means with this?
[snip]
// in the following expression the value of nValue1
// is converted into a double before performing the
// assignment


This is either a typo or you did not show the full code. The only assignment here is on line 4... and that doesn't involve doubles at all (and... technically that's not even an assignment, but whatever).

Line 5 has an addition in which case the contents of nValue1 is extracted and converted to a double prior to addition... which might be what they were trying to illustrate.
operator + does not change values of operands, it returns sum of them which you need to use.

1
2
nValue + 1.0; //calculates sum and returns 2.0 as you do not use this value it dissapears
nValue = nValue + 1.0; //calculates and returns 2.0, which get truncated to 2 and assigned to nValue 
Makes more sense now, thanks
Topic archived. No new replies allowed.