Hi...


I am a bit new to programming, and I'm trying to learn C++. I was wondering if there was a way to copy the contents of one variable into another... So that, for example:

int x=5;
int y;
(Some fancy code here involving x and y);
(y=5 but it is not related at all to x. If x is assigned a value of 10438478234 later in the code, y will still equal 5)

The reason is that if I use variable assingment or pointers, and x changes, then so will y... If you please, list a code or method in order to achieve this data transfer

:icon_smile: Thank you,

If you want 2 variables to refer to the same data, you can also use references:

int x = 5;
   int &y = x;
   
   cout << x << "," << y << endl;
   x = 10;
   cout << x << "," << y << endl;
   y = 15;
   cout << x << "," << y << endl;

output:
5,5
10,10
15,15

You missed my point. What I want is that if I change x, y is not affected.

Thank you!

Ok...

int x =3;
int y= 2;
cout << "x: " << x << " y: " << y << endl;
y=x;
cout << "x: " << x << " y: " << y << endl;
x=10;
cout << "x: " << x << " y: " << y << endl;

output:

x: 3 y: 2
x: 3 y: 3
x: 10 y: 3

It does work like that?? But what about the "x=y" part, followed by "x=10"???? Doesn't that say "x has same value as y, and x is now 10" Doesn't that mean that y will also be 10?? (Please excuse my noobish questions, I'm just staring with this thing!!!)

You sound like a mathematician, not a programmer.

In programming, x = 5 means set x to 5. y = x means set x to the value of y (the old value of x is discarded).

er...

look at it this way

when there is a = sign remember that it is an assignment operator not an "equal" sign

anything on the left is assigned to what is on the right

But what about the "x=y" part, followed by "x=10"???? Doesn't that say "x has same value as y, and x is now 10" Doesn't that mean that y will also be 10??

Looks like you read it wrong.
the only variable assignment he made was y = x

cheers

You sound like a mathematician, not a programmer.

In programming, x = 5 means set x to 5. y = x means set x to the value of y (the old value of x is discarded).

That should have been x = y. The complexity of the statement must have confounded me..

commented: Haha, next time I'll make ik less complex ;) +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.