Variables created inside if-statements

35 views (last 30 days)
gire
gire on 19 Jun 2013
Hello,
Is there a way to avoid/throw a warning/throw an error when a variable is created inside an if-statement?
For example:
if some_condition
% This variable did not exist before the if-statement
something = rand(5);
end
result = SOMEFUNCTION(something);
If the condition some_condition is not fulfilled, the program will crash. This is a really bad practice and it is allowed by Matlab without a warning. Unfortunately the code I am maintaining is full with these cases.
In general, it would be better if Matlab throws an error whenever a variable is created inside an if-statement even if the if-elseif-else case covers all the possible outcomes.
  3 Comments
gire
gire on 3 Jul 2013
Hi dpb: unfortunately, leaving the responsibility to the programmer is unrealistic.
mlint gives the same warnings/errors as Matlab's editor.
Thanks
Jan
Jan on 3 Jul 2013
@gire: It is not surprising that MLint creates the same messages as the editor, because MLint does create the messages in the editor.

Sign in to comment.

Accepted Answer

Jan
Jan on 3 Jul 2013
Edited: Jan on 3 Jul 2013
Leaving the responsibility to the programmer is not "unrealistic" but the only possible solution. There is simply no way to make a program bullet-proof, if the programmer is messy.
If you have to maintain code, which is full of such bad programming patterns, you are in a bad luck. Such "brown field projects" are extremely prone to errors and the most efficient and most secure method is to delete the junk and rewrite it from scratch. Sorry if this sounds pessimistic, but this is the best answer I can offer based on over 30 years of programming. You got a piece of garbage and there is no way to polish it until it is reliable, fast and easy to debug.
Throwing an error if a variable is defined inside an IF block is not an option. This could be an intented behavior and caught later by an exist('something', 'var'). I personally detest this, but there are many many other codes around, which use this method.
Remember that this is possible many other programming languages also, e.g. when you declare a pointer in C and use the contents it points to. And notice that Matlab's possibility to EVAL and ASSIGNIN will make it even impossible to check the code automatically for forgotton definitions.
  1 Comment
gire
gire on 4 Jul 2013
Hi Jan, There is no question regarding the quality of the code I am maintaining.
Given the level of detail mlint is capable of, I thought it could be possible mlint also detects this case.
Thanks

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!