-
Newb needs help
hey all im not that new i started awhile ago but quit and now im starting over from the begining. I'm learning C++ from a book "C++ for dummies." Right now im at
Listing 2-3: "copying a value from one Variable to Another"
Code:
#include <iostream>
#include <stdlib.h>
int main()
{
int start = 50;
int finish;
finish = start;
cout << finish << endl;
getch ();
return 0;
}
now i was good at the begining of the variable section but now this part has completly lost me. Can anyone help me plz
-
Inferno,
As long as the variables are of the same type, they can pass values between them. Or, put another way, in the above code, start is declared as type 'int'. It is 'declared' as type int, but also 'initialised' in the same instance. You could have also written this:
Code:
int start;
start = 50;
They way it is written in the book simply does both steps at once. The next line 'declares' the integer varible 'finish'. No value is assigned to 'finish' at this point. On the very next line though, it is assigned a value. That value is whatever the value of 'start' is. 'start' was declared and initialised on the same line, to the value of 50. That is 'start's' value, so finish now has the value 50 also.
Just a point that you may not be aware of. In C and C++, the = sign does not mean "is equal to" like in traditional maths. In C/C++, this symbol meas, take the value that is on the right of the symbol (=) and make it the new value of the varible that is on the left.
I hope I helped,
Nick.
(As far as cout << goes, don't worry about it yet. Read on and it'll all make sense later.)
-
Think of variables as boxes that can hold one thing, and one thing only. Here, I'll draw an illustration to show it better:
Illustration 1:
Ok, so we've got the variable start and finish, at this stage each one is, well, empty, because we haven't assigned anything to them.
Code:
int start;
int finish;
So we create the two variables, now we can put stuff in them.
Illustration 2:
This code puts the value 50 inside of the start box. As you can see in the illustration, there is now a 50 inside of the start box.
Illustration 3:
This is the fun part, in this code it does 2 things. First it gets the value of start by "looking" in the box at the contents of it. We know that start contains the value 50, so basically what we have now is this:
Then the next step works just like when we initialized the start variable at the beginning. It merely places the value 50 in to the finish box, making finish "equal" 50.
-Hope that helps!
-
Yes it did help....thnxs i appriciate :D