您的位置:首页 > 编程语言 > C语言/C++

C语言解释器-12 控制结构之break、continue和return

2013-03-28 17:21 363 查看
这三种控制结构都必须结合上下文环境共同作用。看起来它们更像是一种标记。因此上,它们的实现也相当简单:

public class Break : ControlFlow
    {
        public override void Print(int tabs = 0)
        {
            Debug.WriteLine(new string('\t', tabs) + "break;");            
        }
    }




public class Continue : ControlFlow
    {
        public override void Print(int tabs = 0)
        {
            Debug.WriteLine(new string('\t', tabs) + "continue;");
        }
    }


return多了一个返回值的表达式:

public class Return : ControlFlow
    {
        public Expression.ExpressionNode Expression;

        public override void Print(int tabs = 0)
        {
            if (Expression == null)
                Debug.WriteLine(new string('\t', tabs) + "return ;");
            else
            {
                Debug.WriteLine(new string('\t', tabs) + "return " + Expression.ToString());
            }
        }
    }



一切需要回溯到Block,在Block运行时,会检测这三种控制结构:

public override void Run(Context ctx)
        {
            if (IsFirstRunning)
            {
                Block parentBlock = this.ParentBlock;

                if (parentBlock != null)
                {
                    this.OnReturn += parentBlock.OnReturn;
                    this.OnBreak += parentBlock.OnBreak;
                    this.OnContinue += parentBlock.OnContinue;
                }

                IsFirstRunning = false;
            }

            foreach (Context stx in Children)
            {
                if (stx is ControlFlow.ControlFlow)
                {
                    if (!ExecuteControlFlow(stx))
                        break;


再看ExecuteControlFlow():

private bool ExecuteControlFlow(Context stx)
        {
            if (stx is ControlFlow.Return)
            {
                if (OnReturn != null)
                    OnReturn(this, stx as ControlFlow.Return);

                return false;
            }
            else
            {
                if (stx is ControlFlow.Break)
                {
                    if (OnBreak != null)
                        OnBreak(this);

                    return false;
                }
                else
                    if (stx is ControlFlow.Continue)
                    {
                        if (OnContinue != null)
                            OnContinue(this);

                        return false;
                    }
                    else
                        stx.Run(this);
            }

            return true;
        }


通过返回false来立即中止上层Block的运行循环。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: