代码之家  ›  专栏  ›  技术社区  ›  Treb

是否将执行逻辑表达式中的所有方法?

  •  0
  • Treb  · 技术社区  · 16 年前

    在c中,给出了两种方法

     bool Action1(object Data);
    bool Action2(object Data);
    

    用于 if 如下声明:

    if ( Action1(Data) || (Action2(Data) )
    {
        PerformOtherAction();
    }
    

    Action2() 如果 Action1() 返回true,或者编译器优化阻止了这种情况,因为已经知道表达式的计算结果为 true ?

    5 回复  |  直到 16 年前
        1
  •  5
  •   Patrick McDonald    16 年前

    只有在action1()返回false时才会调用action2()。

    这在概念上类似于

    if (Action1(Data))
    {
        PerformOtherAction();
    } 
    else if (Action2(Data))
    {
        PerformOtherAction();
    } 
    
        2
  •  7
  •   Andrew Hare    16 年前

    不,C支持逻辑短路,所以如果 Action1 返回 true 它永远不会评估 Action2 .

    这个简单的例子展示了C如何处理逻辑短路:

    using System;
    
    class Program
    {
        static void Main()
        {
            if (True() || False()) { }  // outputs just "true"
            if (False() || True()) { }  // outputs "false" and "true"
            if (False() && True()) { }  // outputs just "false"
            if (True() && False()) { }  // outputs "true" and "false"
        }
    
        static bool True()
        {
            Console.WriteLine("true");
            return true;
        }
    
        static bool False()
        {
            Console.WriteLine("false");
            return false;
        }
    }
    
        3
  •  2
  •   Dmitri Nesteruk    16 年前

    您可以使用单个或&来执行这两个方法。这是脑力测试C考试期望你知道的技巧之一。可能在现实世界中没有任何用处,但还是很高兴知道。此外,它还可以让你以创造性和迂回的方式迷惑你的同事。

        4
  •  1
  •   Two Bit Gangster    16 年前

    如果action1返回true,则不会调用action2,这是由于短路评估的规则。注意,这是一个运行时优化,而不是编译时优化。

        5
  •  1
  •   Harper Shelby damiankolasa    16 年前

    如果action1()返回true,则不会计算action2()。C(C和C++)使用短路评估。 MSDN Link 这里验证它。