【发布时间】:2019-05-16 05:39:52
【问题描述】:
与我之前的question 相关,我尝试创建一个函数present() 来检查可选参数的存在。但是,下面的代码
proc present( x ) { return x.type != void; }
proc test( a: ?T = _void )
{
writeln();
writeln( "test| a = ", a );
writeln( "test| condition = ", a.type != void );
writeln( "test| present( a ) = ", present( a ) );
if present( a ) // error (Line 1)
// if a.type != void // works (Line 2)
{
a = 10;
}
}
// no optional arg
test();
// pass an optional array
var arr: [1..5] int;
test( a = arr );
writeln();
writeln( "main| arr = ", arr );
给出编译时错误
mytest.chpl:3: In function 'test':
mytest.chpl:13: error: illegal lvalue in assignment
mytest.chpl:13: error: a void variable cannot be assigned
这表示a = 10; 行有问题。另一方面,如果我使用第 2 行而不是第 1 行,则代码按预期工作:
test| a =
test| condition = false
test| present( a ) = false
test| a = 0 0 0 0 0
test| condition = true
test| present( a ) = true
main| arr = 10 10 10 10 10
另外,如果我将第 1 行或第 2 行替换为 if isArray( a ),代码也可以工作。这是否意味着我们需要让编译器明确知道a 为_void 时未到达a = 10; 行? (换句话说,present() 是否不足以让编译器知道它,因为测试条件“隐藏”在present() 中?)
【问题讨论】: