3

I was surprised to not see this question here already, and I've either missed the explanation in the docs or it's just not there. It's appreciated. Thanks.

4

Solidity isn't Javascript. Neither of them are there.

switch offers nothing more than a convenient if...else shortcut. I don't know why it wan't implemented in Solidity.

Admittedly subjective, but I've never worked anywhere that didn't explicitly outlaw goto as a bad idea. (Have a read of the infamous 1968(!) "A Case against the GO TO Statement".) In an arena where defensive coding is particularly important, goto isn't something that would be considered good practice.

  • Using switch instead of a large if-else tree can make optimization easier for compilers, because a switch can be directly converted into a branch table. – Jesse Busman Oct 28 '18 at 16:39
  • Although I completely agree that goto should generally be avoided, I'm not sure why JavaScript is brought up in your answer, since JavaScript doesn't (natively) support goto neither AFAIK. Surely you can implement goto functionality easily with JavaScript, but that's the case for all languages with metaprogramming capabilities, and metaprogramming is not a bad thing, albiet for a contract oriented language such as solidity, metaprogramming capabilities may be undesirable and should be avoided. – hellopeach Jul 4 at 7:07
0

There is no goto in Solidity but you can somewhat emulate it using the break and continue statements, which compile directly to jump instructions.

  • break jumps to the code right after the current innermost loop.

  • continue jumps to the start of the current innermost loop.

To jump forwards you can break out of a do ... while(false); loop like this:

do
{
    // Code here is always executed
    if (a) break; // if (a) goto label1;
    // Code here is skipped if a evaluated to true.
}
while (false);
// label1:

To jump backwards you can continue in a while(true) { ... break; } loop:

// label2:
while (true)
{
    // Code here is executed at least once, and repeats while a is true.
    if (a) continue; // if (a) goto label2;
    // Code here is only executed once.
    break;
}

Of course this is not recommended at all :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.