Why use this syntax?
1 回表示 (過去 30 日間)
古いコメントを表示
Hello.
I'm quite new to programming in general, and I wonder if there is some logical reason to do the following.
When reading examples and descriptions of functions I often see:
fileName = 'blabla.txt';
newFile = fopen(fileName);
When I use fopen I type directly in the () instead of creating a variable holding the name, is there a good reason to do it as writen above?
Or is it simply good practice?
0 件のコメント
採用された回答
Adam
2014 年 12 月 3 日
Personally I find it good practice to do the above, especially if the same thing is being used more than once. This is especially true of numbers or booleans where I don't like so-called "magic numbers" or "magic bools".
If you just call a function as:
myFunc( 7, true, 5, false );
it carries no meaning, whereas named variables do.
In your specific example this is not so much the case, but I still prefer to do this. It also makes it easier if, for example the filename is going to come from a UI or some other source where it would naturally be in a variable.
その他の回答 (1 件)
Guillaume
2014 年 12 月 3 日
Most likely, the author plans to reuse filename later on in the code. For example:
filename = 'blabla.txt';
fid = fopen(filename, 'r');
if fid<1
fprintf('Failed to open %s\n', filename);
else
[a, count] = fread(fid, 2000, 'uint8');
if count ~= 2000
fprintf('%s was only %d bytes long\n', filename, count);
end
end
It also allows you to refactor easily later. For example you may decide that filename comes from a function.
If it's only one time use, there's no advantage.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Get Started with MATLAB についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!