本文介绍了In / Out vs Out in Ada的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的Ada问题。如果我有一个程序可以写一个变量,或者我可能不理会它,那它应该是 Out 参数还是 In Out 参数?我想这可以归结为一个问题:

I have a quick Ada question. If I have a procedure where I may write out to a variable, or I might leave it alone, should it be an Out parameter or an In Out parameter? I guess this boils down to the question:

如果调用方调用参数为 Out ,但过程不涉及参数。它看到相同的值吗?未定义行为?

What does the caller see if it calls a procedure with a parameter as Out but the procedure doesn't touch the parameter. Does it see the same value? Undefined behavior?

编译器没有抱怨,因为它看到了对 Out 变量的赋值...只是碰巧是有条件的,可能无法达到条件,并且编译器不会费心检查所有路径。

The compiler doesn't complain because it sees an assignment to the Out variable...it just happens to be in a conditional, where it may not be reached, and the compiler doesn't bother to check all paths.

我怀疑安全的押注是在参数为进出,但我想知道这是否是必要的,或者在样式上更可取。

I suspect the safe bet is marking the parameter as In Out, but I'd like to know if this is necessary or just stylistically preferable.

谢谢!

-prelic

推荐答案

在Ada中,当 out 参数不会对该参数写入任何内容,传递回调用方的结果是未定义。这意味着调用程序中该变量中的任何内容都会在过程返回时被垃圾覆盖。

In Ada, when a procedure with an out parameter does not write anything to that parameter, the result passed back to the caller is something undefined. This means that whatever was in that variable in the caller, gets overwritten by garbage on return from the procedure.

Ada的最佳做法是明确初始化所有 out 参数在过程开始时带有适当的默认值。这样,该过程中的任何代码路径都会将有效数据传递回调用方。

The best practice in Ada is to definitively initialise all out parameters with a suitable default value at the start of the procedure. That way, any code path out of the procedure results in valid data passed back to the caller.

如果调用方中有可能 要通过过程更改,必须使用 in out 参数。

If you have something in the caller that might be changed by a procedure, you must use an in out parameter.

来自:

这篇关于In / Out vs Out in Ada的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:37