此链接说明我们应该使用endfor语句来关闭循环范围for。
但将其替换end为相同行为的结果。
使用end而不是endfor有任何意想不到的副作用吗?
endendfor与关闭循环同义for。
使用的唯一副作用end是您的代码也将与 MATLAB 兼容,这endfor是 Octave 发明的语言的扩展。我建议您不要使用endfor诸如此类的(endif、endfunction、endswitch、endwhile)。
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.