Assignment of value to variable

Asked

Viewed 146 times

0

I have two global variables, which we’ll call To and B, when I make the following assignment:

A:= 5;
B:= A;

Every time I change the value of To, the value of B also changes. If I do

A:= 10

B becomes 10 too. How can I change the value of To without changing the value of B?

  • 3

    You can give more context. This is to happen no.

  • As variables A and B are declared?

  • You need to see if you don’t have a "var" function, something like that. The way the question looks, you can’t reproduce the problem. If you can [Dit] the post with a [mcve], it is easier to have a solution.

  • This behavior will only happen if the variable B is an integer pointer and even then the assignment syntax would be different.

  • Tmc, what you are asking for regardless of the code that comes before is a little groundless, because in the code you are saying that B = A... Either you change this rule or you put an IF to check if you really want to assign the value of a in B.

2 answers

2

In Delphi the code is executed line by line so if you have the following code:

A := 5;
B := A;
showmessage('A=' + IntToStr(A) + '; B=' + IntToStr(B));

Message: A=5; B=5

You are setting the same value as To variable B.
To B have a different value than To simply remove the assignment from it "B := A;" code example:

A := 10;
//B := A;
B := 62;
showmessage('A=' + IntToStr(A) + '; B=' + IntToStr(B));

Message: A=10; B=62

Not being the most correct option (depending on the cases) can still reassign the value of the variable B, example:

A := 10;
B := A;
showmessage('A=' + IntToStr(A) + '; B=' + IntToStr(B));

Message: A=10; B=10

B := 62;
showmessage('A=' + IntToStr(A) + '; B=' + IntToStr(B));

Message: A=10; B=62

There is also one last option which is to assign a new value to To as follows, example:

A := 5;
B := A;
A := 10;
showmessage('A=' + IntToStr(A) + '; B=' + IntToStr(B));

Message: A=10; B=5

-3

Are you declaring that B is equal to To, just when you change To, will change B.

A:= 5;
B:= A; //Aqui que você declara que B é igual a A

One thing you can do is declare B as 5 and change the value of To

A:=5;
B:=5;
A:=10;

Thus, B is not defined as To, so is not changed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.