Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Puzzle : Reachable goto pointing to an unreachable label

Tags:

c#

goto

Here's Eric Lippert's comment from this post:

Now that you know the answer, you can solve this puzzle: write me a program in which there is a reachable goto which goes to an unreachable label. – Eric Lippert Jul 17 at 7:17

I am not able to create a code which will have reachable goto pointing to an unreachable label. Is that even possible? If yes, what would the C# code look like?

Note: Let's not get into discussion about how 'goto' is bad etc. This is a theoretical exercise.

like image 847
SolutionYogi Avatar asked Dec 17 '22 06:12

SolutionYogi


1 Answers

My original answer:

    try
    {
        goto ILikeCheese;
    }
    finally
    {
        throw new InvalidOperationException("You only have cottage cheese.");
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");

Here is without the compiler warning.

    bool jumping = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            jumping = (Environment.NewLine != "\t");
            goto ILikeCheese;
        }

        return;
    }
    finally
    {
        if (jumping)
            throw new InvalidOperationException("You only have cottage cheese.");
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");
like image 146
Sam Harwell Avatar answered Jan 30 '23 08:01

Sam Harwell