Is there a way to avoid/throw a warning/throw an error when a variable is created inside an if-statement?
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.
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.
Play games and win prizes!Learn more