Im a PLC programmer and I am wondering why the reserved word elsif (ie without the E ) is used. I know that elseif or any other combination is not used as reserved words. Is there a history to use this in other Languages. If so why? just to save on typing cause for me I seem to make the mistake of typing the e probably 5 times a day.
Programming languages have never quite agreed on this. Various common languages use:
else if
elseif
elsif
elif
and perhaps others. There's often no good reason for the language designer choosing one over another.
(Bonus points if you can name some languages that use each of the above forms!)
I wonder what type of PLC you are programming, I just found out rockwells structured text uses elsif, and Ada did but thats not really for PLCs is it?
I am told it's Syntactic sugar, the elsif is there so you don't have your code cluttered up by lots of brackets
if cond1 then
funct1
elsif cond2 then
funct2
elsif cond3 then
funct3
else
funct4
end if
becomes
if cond1 then
funct1
else (if cond2 then
funct2
else (if cond3 then
funct3
else funct4
))
end if
As far as the origin goes my guess would be it has just stuck around since Ada or whatever was before that.
Pascal is the father of Structured Text (or SCL as called by Siemens) used in PLCs.
Related
some hacker folks are debating over this issue and I felt like getting the right answer here
If (condition_c){
While (condition_c){
//code here
}
}
Is there any case or situation that this can be done?
If yes, give a situation that justify ur answer.
This is possible in all languages that support IF and WHILE since you're just simply composing the two constructs. There are limited situations in which this would actually be meaningful. Assuming you don't have any other code between your IF and your WHILE (just like you don't in your example) there's really only one reason this would be meaningful and that's if you have side effects in your condition. Consider the following snippet of Perl code.
if ($line = <STDIN>) {
while ($line = <STDIN>) {
print $line;
}
}
In this program, the IF is meaningful because the state of my input buffer is different the second time I compare it. This snippet of code could be useful if I wanted to, for example, print out all the lines of a comma-separated value file but drop the header, which is the first line.
Now you might say to me that this could be written better by not putting the first read inside the IF but perhaps I want to tack and ELSE onto that IF. There's always more than one way to write stuff so keep that in mind.
So in conclusion this code is meaningfully different in the event that the condition has side effects. Other examples could be something like "$x-- == 0" or "f(x)" where f has some side effect. If it's just a plain-old boolean value, then no.
This is almost certainly possible in the majority of programming languages that support such constructs. It is unlikely to be useful in any of them.
A friend of mine was learning to program and he asked me why there isn't an "and if" / "also if" / "or if" statement (non-exclusive or), where multiple, independent test conditions with independent results can be met that would prevent any "else" conditions from triggering. Edit: I think my choice of "or" may have been a bad keyword here, because the or keyword is usually evaluated lazily, so the second branch never fires. What I'm talking about is something where all the true conditions fire, but if there are no true conditions among the or ifs, then you move on to the else/elif branch.
Here is an example (using python syntax):
if a:
print('a evaluates True')
orif b:
print('b evaluates True')
else:
print('Both a and b evaluate False')
The way this is different from elif is that in the event that both a and b are true, the output of this would be:
a evaluates True
b evaluates True
Whereas in an elif, the output of that conditional would be:
a evaluates True
I got on my "I've been programming for years" hat and started to explain, "Well, of course there's no orif statement because...", but I couldn't come up with a good reason. A good example of this concept is fizzbuzz, where you are asked to print all numbers between 1 and 100, but with all numbers divisible by 3 replaced by fizz, all numbers divisible by 5 replaced by buzz and all numbers divisible by both 3 and 5 replaced by fizzbuzz. Using an "orif" syntax, it can be accomplished with a single conditional:
for x in range(1, 100):
outstr = ""
if x%3 == 0:
outstr += "fizz"
orif x%5 == 0:
outstr += "buzz"
else:
outstr = x
print(x)
But without it, you're stuck with something less elegant, either switching to three conditionals and at least one additional modulo evaluation:
for x in range(0, 100):
outstr = ""
if x%3 == 0:
outstr += "fizz"
if x%5 == 0:
outstr += "buzz"
if not x%15 == 0: # Could also be not (x%3 and x%5)
outstr = x
print(x)
Or you can avoid the extra modulo operation by storing them ahead of time:
for x in range(0, 100):
outstr = ""
fizz = (x%3 == 0)
buzz = (x%5 == 0)
if fizz:
outstr += "fizz"
if buzz:
outstr += "buzz"
if not (fizz or buzz):
outstr = x
print(x)
There are obviously other ways to accomplish this, but none of them are quite as intuitive as the "orif" structure. Looking back, I've noticed that this is something I've actually come up against many times, where I have a number of conditions with different effects that each need to be evaluated, and a default condition that occurs if none of them are met. I usually "solve" this problem by having an annoying "flag" variable in each of the separate conditionals:
OneConditionMet = False
if a:
# Do the "a" stuff
OneConditionMet = True
if b:
# Do the "b" stuff
OneConditionMet = True
# ...
if n:
# Do the "n" stuff
OneConditionMet = True
if not OneConditionMet:
# Do the default behavior.
Obviously this is a quite inelegant and annoying way to do this, another problem solved by "orif". So, given all these clear reasons for an "orif", I was shocked to find in the Wikipedia article on conditionals that there isn't any mention of anything similar. This makes me think that there's something fundamental I'm missing about why this doesn't work. The only reason I can think of is the fact that as constructed above, the evaluation would need to be slightly less lazy because it would need to check if any "or if" branches occur even if the first "if" condition were met. That's a pretty easy problem to solve, though, because you could just make it so that if you have any or if statements in the conditional tree, then all if statements need to be or if statements, like such:
orif a:
print('a evaluates True')
orif b:
print('b evaluates True')
else:
print('Neither a nor b evaluate True')
So, there's the question - am I missing something that's fundamentally equivalent to this? Am I missing some reason why it's fundamentally unworkable, or is this just a huge missed opportunity?
What you asking for is alternatively described as pattern-matching or decision table. Even so, getting the right behaviour on the false branch is not easy, and I've not seen any languages that do exactly that.
Pattern matching languages (like awk) fire every rule that matches a pattern. You need some extra code to record whether any rule fired and fire the else rule if not.
Decision table software was popular (as a preprocessor) at least 30 years ago. Essentially you put what the tests and actions are into a table, and the system analyses what's left over so as to execute a default action.
Personally, I don't think it's that useful. There are real problems in managing complex sets of if tests, and I don't think this single feature would resolve many of them. In a lot of these cases you can naturally ensure that the else case is detected because some variable never got touched. There are harder combinations that take serious planning to avoid utter confusion.
BTW the use of 'andif' and 'orif' are unhelpful. They really do make one think of something else entirely.
i'm not aware of any. but...
first of all be aware that your 'parallel if' is almost exact equivalent to sequence of standard 'if'. the only difference is just the else clause. and if predicate computation is expensive you can always cache it (like in your example with modulo)
when we are talking about imperative/OOP everyone tries to use inheritance and some functional idioms (like all kinds of 'optional') simply to remove branching. it's being said that the only switch/case statements are allowed inside factories and they should have no logic and do absolutely nothing except returning some kind of enum.
when we are talking about functional programming then it seems this construct is even less useful. functional programs tends be function compositions. each expressions should return a single value and has (almost) none side effects. so this construct would discard return values from almost all branches and would be useful only for non-pure code which should be isolated.
when i try to recall my code from my everyday work i can't really find a place where i would want to use it. so maybe it's simply not needed in general purpose languages. but you can always implement as a macro
I think that orif construct is not a good fit in C because it would be too complicated. All existing C statements have simple syntax and have only one sub-statement. For instance in for you have
for (clause; expression; expression)
statement
Even switch, which is the most complicated one, uses one sub-statement and a trick of using case as labels similar to goto labels. The orif would be very different - it would need an arbitrary number of sub-statements and their corresponding conditions.
From this perspective, orif would be a beast of completely different kind than all existing C statements. Today, though many popular languages provide various constructs not found in C, the fundamental statements like loops and conditionals are in many cases inherited from C (with changes obviously but still). And the arguments I presented for C apply to many other languages too. (Not all, since e.g. Python has similar elif.) I guess that at least partially explains why there is no orif.
I'm working on a simple programming language for kids, based on Karel. For controlling program flow, I currently provide these facilities (in pseudocode):
defining parameterless procedures
if [not] EXPRESSION STATEMENT
while [not] EXPRESSION STATEMENT
I don't have any means to return from a procedure, and I don't provide the else statement.
Take the following code for an example:
if something
statement1
if not something
statement2
The execution of code flows to if, executing statement1 if something is true;
then testing if something is not true (but the state of the program has changed!), then executing statement2. This can lead to both tests succeeding.
Does this limit the programmer? So far I've been able to solve all of my example problems by just using if ... if not ..., or using if not first, then if.
So, my question is:
Is adding the else statement necessary? It would make the language a bit more complicated with having more keywords. Are all problems that would be solvable with else statement solvable also without it, albeit more complicated?
Or is omitting the else statement actually making the language more complicated and counter-intuitive?
If something is expensive to evaluate then your language with else might give a problem because the evaluation will be performed twice.
Another potential problem is that if statement1 can modify the value of something you may end up with both tests succeeding - something that could not happen if you used else.
Of course these problems can be mitigated by storing the result in a temporary local variable:
bool result = something
if result
statement1
if not result
statement2
So no you aren't limiting the programmer in what is possible - everything that can be done with else can be done without it by using the above approach. But it is a little more code to write each time and it introduces a few new potential problems for the unwary programmer that would be avoided if you allowed else.
Semantically speaking you could avoid having the else construct, but from practical point of view I don't see any necessity of doing that.
The concept of do something if something is true, otherwise something else is not so strange and confusing, it sounds actually quite straightforward that having to evaluate and negate an expression again just to check its negation.. it's a free (in sense of "with no added complexity") optional synctactic sugar that is automatic when developing a language.
I saw many other features really more useless compared to the else statement.. then you are not considering the fact that evaluating a condition twice maybe harmful for side-effects or for complexity (wasted cpu?) or for the fact itself that you already have calculated it and you have to do it again for a lack of the language not because it's senseful.
If something has side-effects than your approach will cause them to happen twice, which is probably not what you want.
IMHO It's bad idea to teach children to duplicate code.
The question I asked might be closed, But i just want to know that is it necessary to write else part of every if condition. One of my senior programmer said me that "you should write else part in every if condition" . Suppose we have no condition for write in else part then what should we do ? I assume a healthy discussion will going on here....
That's a horrible idea. You end up with code of the form:
if (something) {
doSomething();
} else {
}
How anyone could think that's more readable or maintainable that not having an else at all is beyond me. It sounds like one of those rules made up by people who have too much free time on their hands. Get them fired as quickly as you can, or at least move away calmly and quietly :-)
No, you certainly don't have to - at least in most languages. (You didn't specify; it's quite possible that there's a language which does enforce this.) Here's an example where I certainly wouldn't:
public void DoSomething(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
// Do stuff
}
Now you could put the main work of the method into an "else" clause here - but it would increase nesting unnecessarily. Add a few more conditions and the whole thing becomes an unreadable mess.
This pattern of "early out" is reasonably common, in my experience - and goes for return values as well as exceptions. I know there are some who favour a single return point from a method, but in the languages I work with (Java, C#) that can often lead to significantly less readable code and deeper nesting.
Now, there's one situation where there's more scope for debate, and that's where both branches are terminal, but neither of them is effectively a shortcut:
public int DoSomething()
{
// Do some work
if (conditionBasedOnPreviousWork)
{
log.Info("Condition met; returning discount");
return discount;
}
else
{
log.Info("Condition not met; returning original price");
return originalPrice;
}
}
(Note that I've deliberately given both branches more work to do than just returning - otherwise a conditional statement would be appropriate.)
Would this be more readable without the "else"? That's really a matter of personal choice, and I'm not going to claim I'm always consistent. Having both branches equally indented gives them equal weight somehow - and perhaps encourages the possibility of refactoring later by reversing the condition... whereas if we had just dropped through to the "return original price", the refactoring of putting that into an if block and moving the discount case out of an if block would be less obviously correct at first glance.
In imperative languages like Java and C, if - else is a statement and does not return a value. So you can happily write only the if part and go on. And I think that it is the better practice rather than adding empty elses after every if.
However in functional languages like Haskell and Clojure, if is an expression and it must return a value. So it must be succeeded with an else. However there are still cases where you may not need an else section. Clojure, for such cases, has a when macro which wraps if - else to return nil in the else section and avoid writing it.
(when (met? somecondition)
(dosomething))
Danger! Danger, Will Robinson!
http://en.wikipedia.org/wiki/Cargo_cult_programming
Is the inclusion of empty else { } blocks going to somehow improve the quality, readability, or robustness of your code? I think not.
Looking at this purely from a semantic point of view - I cannot think of a single case
where there is not an implicit else for every if.
if the car is not stopped before I reach the wall I will crash, else I will not crash.
Semantics aside:
The answer to that question depends on the environment, and what the result of a mistake is.
Business code? Do what your coding standards say.
IMHO you will find that spelling it out, although initially it seems like too much work, will become invaluable 10 years from now when you revisit that code. But, it certainly would not be the end of the world if you missed an important 'anti-condition'.
However: Security, Safety or Life Critical code? That's a different story.
In this case you want to do two things.
First:Rather than testing for a fault, you want to prove there is not a fault. This requires a pessimistic view on entry to any module. You assume everything is wrong
until you prove it is correct.
Second: in life critical: You NEVER want to hurt a patient.:
bool everyThingIsSafe = true;
if(darnThereIsAProblem())
{
reportToUserEndOfWorld();
}
return everyThingIsSafe;
Oops. I forgot to set everyThingIsSafe false.
The routine that called this snippit is now lied to. Had I initialized evertThingIsSafe to false - I'm always safe, but now I need the else clause to indicate that there wasn't an error.
And yes, I could have changed this to a positive test - but then I need the else
to handle the fault.
And yes, I could have assigned everyThingIsSafe() the immediate return of the check.
And then tested the flag to report a problem. An implicit else, why not be explicit?
Strictly speaking, the implicit else this represents is reasonable.
To an FDA/safety auditor, maybe not.
If it's explicit, can point to the test, its else, and that I handled both conditions clearly.
I've been coding for medical devices for 25 years. In this case, you want the else, you want the default in the case, and they are never empty. You want to know exactly what is going to happen, or as near as you can. Because overlooking a condition could kill someone.
Look up Therac-25. 8 severely injured. 3 dead.
I know I am late but I did a lot of thinking over this and wanted to share my results.
In critical code, it is imperative for every branch is accounted for. Writing an else is not necessary, but leave a mark that else is not necessary and why. This will help the reviewer. Observe:
//negatives should be fixed
if(a < 0) {
a+=m;
}
//else value is positive
No, It's not required to write the else part for the if statement.
In fact most of the developers prefer and recommend to avoid the else block.
that is
Instead of writing
if (number >= 18) {
let allow_user = true;
} else {
let allow_user = false;
}
Most of the developers prefer:
let allow_user = false;
if (number >= 18) {
let allow_user = true;
}
Sometimes there is no else part....and including an empty one just makes the code less readable imho.
No, you don't have to ..
Also, I don't think that it is a good idea for readability, since you will have lots of empty else blocks. which will not be pretty to see.
This is purely a matter of style and clarity. It's easy to imagine if statements, particularly simple ones, for which an else would be quite superfluous. But when you have a more complex conditional, perhaps handling a number of various cases, it can often be clarifying to explicitly declare that otherwise, nothing ought to be done. In these cases, I'd leave a // do nothing comment in the otherwise empty else to it clear that the space is intentionally left blank.
No, but I personally choose to always include encapsulating braces to avoid
if (someCondition)
bar();
notbar(); //won't be run conditionally, though it looks like it might
foo();
I'd write
if (someCondition){
bar();
notbar(); //will be run
}
foo();
def in_num(num):
if num % 3 == 0:
print("fizz")
if num % 5 == 0:
print("buzz")
if (num % 3 !=0) and (num % 5 !=0):
print(num)
see in this code else statement is not necessary.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Conditional styles: if (0 == resultIndex) vs if (resultIndex ==0)
I've seen both in code, and I do not know why one is better over the other, but which do you prefer to use, and why?
The if(null == var) practice comes from C, where you could accidentally write if(var = null) (note the assignment operator), which would compile (since in C everything not 0 is true) but will be a semantic error. So if(null == var) is a defensive practice, since null is an lvalue (again C/C++ terminology) and lvalues cannot be assigned to.
In modern languages (particularly in C#) compiler will warn you if you do assignment in if statement.
I would say var==null because it's more like what you would actually say. "If my variable is null..." makes more sense than any variant of "If null is my variable..." or "If nothing is my variable..." etc.
I prefer to use (var==null) myself. It makes more sense to me, since I'm checking "if var is null". The other order comes across when I read it as "if null is var", which never makes sense. I also like how VB.NET makes it quite readable, and makes a check for null different from other comparisons, with "if var is nothing".
They both have the same functionality and produce the same result. The choice is purely a personal one to make.
I personally prefer the first because "var is null" or "var equals null" reads better than "null is var" or "var is null".
Some people prefer the second and claim it reduces typo-induced bugs because null = var causes an error while var = null still compiles. These days, however, compilers issue warnings for this, so I believe it is a moot point.
Typically I tend to go unknown value then known value when I am comparing two values. That way I know first what I am looking in, giving context to the test. Most languages don't care, but I think some may.
Language-agnostic?
In Scheme, no ambiguity:
(null? var)