开发者

simultaneous variable assignation in pascal

I wish to do simultaneous variable assignment in Pascal.

As far as I know, it's not possible. Googling on the issue, I can see that many programming languages implement that, but I can't find how to do it in Pascal.

For example, in Python I can do this:

(x, y) = (y, x)

In Pascal, I need an additional variable to hold the value of x before it's removed, something like this:

bubble := x;
x := y;
y := bubble;

So, is there simultaneous assignment in Pascal, or should I rewrite the code to something like the bubble thing above?

I don't just have to do swaps; sometimes I have to do things like this:

(x,y) = (x+1,y+x)

Would it be ok to do it like the following?

old_x := x;
old_y := y;
x := x + 1; // maybe x := 开发者_开发知识库old_x + 1;
y := old_y + old_x;


PASCAL does not contain a simultaneous variable assignment.

Nor does it contain a SWAP(X,Y) predefined procedure.

You have to do it yourself.

You might want to consider buying a copy of [Jensen & Wirth]. It is still the best reference manual available on the language. If you are using one of the Borland PASCAL systems, use the manual that came with it: Borland made some incompatible changes, that nevertheless made the language significantly easier to use.


I'm not familiar at all with Pascal, but I can't find any special swap function that does what you want.

In any case, what you're doing is perfectly reasonable; any standard implementation of swap requires a temporary variable to hold one of the values being swapped. The only thing I would change in the code you have written above is to rename the variable to temp, to make it clear that the variable only exists temporarily for the purposes of the swap:

temp := x;
x := y;
y := temp;

EDIT: There's also nothing wrong with what you're doing when changing x and y. If you need to keep the old value as part of your calculations, it's perfectly fine to assign the old value to a variable and then use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜