Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Variables created inside if-statements

Asked by 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

dpb on 19 Jun 2013

Try mlint

Other than that, it's programmer's responsibility to design the code and implement it correctly.... :)

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 Simon 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.

gire

Products

1 Answer

Answer by Jan Simon on 3 Jul 2013
Edited by Jan Simon on 3 Jul 2013
Accepted answer

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 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

Jan Simon

Contact us