Why use an "if" statement to encapsulate a block of code?

1 view (last 30 days)
I notice that many users encapsulate their code inside an if statement such as
if true
...
(code)
...
end
What is the purpose for this? Is it variable scoping?
  2 Comments
Bob Thompson
Bob Thompson on 2 Mar 2018
Are you talking about here on the forums? They do that simply because when you push the "{}Code" button it pops up that stuff automatically.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 2 Mar 2018
No, it has nothing to do with variable scoping. It is an artifact of the code formatting process for the web site.
The best way to format code for posting here is to paste in the code, then use your mouse to highlight it, and then to click on the '{} Code' button: that will format what is highlighted.
But some people instead press the '{} Code' button without having posted any code first or having highlighted anything. They might possibly be expecting that the button will bring up a code-entry window. Anyhow, when you press that button with nothing selected, the editor inserts
if true
% code
end
and if the user happens to then insert the code immediately after that with no empty lines, then the format routines will happen to interpret that as a request to indent and format what follows to the first empty line. This is nothing special about "if true" and so on: it just happens to be the reaction of the format routines to a block in which the first line is indented by two spaces.
Some people, having pressed the button and received the
if true
% code
end
block, interpret that as indicating that they should replace the "% code" block with their actual code. Again, that will just happen to result in their code being formatted until the first empty line.
The "if true" does not mean anything special to MATLAB; it is just down to the web site. The web site could just as easily have instead put in
%insert code immediately after this line with no empty lines
or something like that.

More Answers (0)

Categories

Find more on Historical Contests in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!