Octave中end语句可以代替endfor语句吗?

Sau*_*ahu 2 for-loop octave

此链接说明我们应该使用endfor语句来关闭循环范围for。

但将其替换end为相同行为的结果。

使用end而不是endfor有任何意想不到的副作用吗?

Cri*_*ngo 7

endendfor与关闭循环同义for。

使用的唯一副作用end是您的代码也将与 MATLAB 兼容,这endfor是 Octave 发明的语言的扩展。我建议您不要使用endfor诸如此类的(endif、endfunction、endswitch、endwhile)。


Tas*_*nou 6

In practice I mostly agree with Cris' answer, and I follow the same advice in principle. However, I feel a need to play devil's advocate here, because it makes it sound like the octave developer's decision to provide these keywords was misguided, when actually there is good reason, and knowing the benefits of using endfor, endif allows you to make an informed decision on when and why to avoid them.

Allow me to demonstrate their usefulness with an example:

function f(a)
    if a == 1
       disp('a == 1')
    else if a == 2
       disp('a == 2')
    else
       disp('a == 3')
    end
    disp('do some very important thing here that absolutely must be done always')
end
Run Code Online (Sandbox Code Playgroud)

Can you spot the subtle but deadly bug here?

Whereas if you try to run this code:

function f(a)
    if a == 1
       disp('a == 1')
    else if a == 2
       disp('a == 2')
    else
       disp('a == 3')
    endif
    disp('do important thing')
endfunction
Run Code Online (Sandbox Code Playgroud)

octave will immediately warn you that something is awfully wrong, and it will stop you from shooting yourself on the foot.

There are many other situations where endifs and endfors would protect you when simple end wouldn't. And, at the very least, they provide a very strong visual signposting of where you are in the code (did I just close that for loop, or did I just exit an if block). Especially given the state of most academic code out there, which is usually a bunch of unindented spaghetti code with lots of nested if and for blocks that goes on for miles in a single file. Chances are if you follow good software engineering principles, clean, modular, properly indented code, then the extra layer of protection added by writing endfor instead of end is probably overkill. But just because this is the case doesn't mean they're not there for good reason.

But, I agree, if you desire matlab compatibility, and you probably do, then it's best you use the 'slightly less safe but ultimately compatible' version.

Ironically, I often find myself writing code that looks like this:

if something
  % large block of code here
end % if
Run Code Online (Sandbox Code Playgroud)

just to be matlab compatible, but still make it visually clear that the block that just closed was actually an if block.

  • 这是一个很好的论点。感谢您分享您的观点!我认为 linter 应该能够避免这种类型的错误,但是关于大多数 MATLAB/Octave 代码都是缩进不一致的学术意大利面条,你是 100% 正确的。 (4认同)
  • @SauravSahu:在该示例中,“else if”启动一个新的“if”语句。有两个以“end”结尾的“if”语句。“function”没有“end”,但这在 MATLAB 中是合法的。该代码旨在使用“elseif”而不是“else if”。 (2认同)