C# Puzzle : Reachable goto pointing to an unreacha

2020-02-11 07:13发布

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.

标签: c# goto
3条回答
The star\"
2楼-- · 2020-02-11 07:36

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.");
查看更多
等我变得足够好
3楼-- · 2020-02-11 07:58

By the way if you use goto the csharp compiler for example for this case without finally block changes the code to a version without goto.

using System;
public class InternalTesting
{
public static void Main(string[] args)
{
  bool jumping = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            jumping = (Environment.NewLine != "\t");
            goto ILikeCheese;
        }
    else{
            return;
    }
    }
    finally
    {
        if (jumping)
{
            //throw new InvalidOperationException("You only have cottage cheese.");
    Console.WriteLine("Test Me Deeply");
}
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");
}
}

Turns To:

public static void Main(string[] args)
{
    bool flag = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            flag = Environment.NewLine != "\t";
        }
        else
        {
            return;
        }
    }
    finally
    {
        if (flag)
        {
            Console.WriteLine("Test Me Deeply");
        }
    }
    Console.WriteLine("MMM. Cheese is yummy.");
}
查看更多
成全新的幸福
4楼-- · 2020-02-11 08:00
goto cant_reach_me;

try{
cant_reach_me:
}
catch{}

This is either a compile or runtime error, I can not remember. The label must be outside the try/catch block

查看更多
登录 后发表回答