In/Out vs Out in Ada

2019-05-01 15:42发布

问题:

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:

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?

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.

Thanks!

-prelic

回答1:

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.

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.

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

From the Ada 95 RM 6.4.1 (15):

For any other type, the formal parameter is uninitialized. If composite, a view conversion of the actual parameter to the nominal subtype of the formal is evaluated (which might raise Constraint_Error), and the actual subtype of the formal is that of the view conversion. If elementary, the actual subtype of the formal is given by its nominal subtype.



标签: ada