-3

This seems to execute like an infinite loop.

a:
    echo "Statement 1 \n";
b:
    echo "Statement 2 \n";
if(1 > 2)
    goto a;
else
    goto b;

But this works correctly.

if(1 > 2)
    goto a;
else
    goto b;
a:
    echo "Statement 1 \n";
b:
    echo "Statement 2 \n";

What makes the difference.How can i execute some block of code again like in the first case.Example

$b = 1;
$c = 2;
$a = $b+$c;

if($a > $ b)
  // here i want to cal $a = $b+$c; without using function or copy pasting the code.
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91

2 Answers2

2

goto will jump to that part of the code. So in the first case you jump up and start again at b: and then you do that over and over again. But in the second case you jump down.

WizKid
  • 4,888
  • 2
  • 23
  • 23
  • 1
    It doesn't just execute that first line under your `b:` label. As WizKid says, it **jumps** and continues on with all the code after, thus giving you your infinite loop – ElefantPhace May 20 '14 at 03:40
2

It is an infinite loop because... your code is an infinite loop!

    a:
        echo "...";
.-- b: <------------.
|       echo "..."; |
|   if(1 > 2)       |
|       goto a;     |
|   else            |
`-----> goto b; ----´

It will output:

Statement 1
Statement 2
Statement 2
Statement 2
Statement 2
[...]

Named sections of code (a: and b:) do not stop the script; they are just names that you can jump to. Named sections of code will always be executed if reached.

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52