dimanche 28 avril 2019

Why is there no "return if" statement in programming languages?

First of all, I would like to point out that my theoretical knowledge of the anatomy of programming languages is not as deep as it should be, and I apologize in advance.

This may also be a stupid question, I apologize for that, but I have been wondering for some time why there is no return if statement or at least syntactic sugar for it in (at least the ones I'm familiar with) programming languages, especially in languages like Python or Lua, which are relatively high-level and often allow an alternative spelling with syntactic sugar.

Take the following code, for example:

if(x > y) {
    return x;
}

Of course you know directly what happens, if x > y is true x is returned. However, one could now argue the following:

  1. Depending on the programming language several lines are needed for a simple statement. Of course you could write it inline like if (x > y) { return x }
  2. It doesn't "sound" that great: if x > y, x gets returned

Just to make it clear, I don't mean to say that the "traditional" way is bad, I'm just asking out of interest.

If you were to use a statement like "return if", the above statement could look like this:

return x if (x > y);

It is a one-liner and it reads well x gets returned if x > y


Now I asked myself the following questions:

  1. Is this simply a design decision?
  2. Does a return if syntax cause unnecessary complications for the parser/compiler?
  3. If it's neither the first nor the second, then what is it? Coincidence? I will certainly not be the first one to think about it in all the decades of programming.

Aucun commentaire:

Enregistrer un commentaire