Thread: Expression parsing specification?

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    26

    Expression parsing specification?

    Basically, I want this:

    Code:
    if (v1)
      if (va==vb)
        f();
    
    else if (v2)
      if (vc==vd)
        f();
    Would I be able to write the above like this instead ?

    Code:
    if (((v1) && (va==vb)) || ((v2) && (vc==vd)))
      f();
    I would assume so (although not tested).

    However, in what order is the above guaranteed to be evaluated? Assume v1 & v2 are zero, will the produced code just check v1 and v2, and ignore va,vb,vc and vd? Or will it first check va==vb before checking v1 != 0 ? (ie, will it run exactly the same as first example?)

    I want the code to run as quick as possible. I don't want to use multiple if statements and multiple possible function calls, unless there would be a speed improvement in doing so.
    Last edited by Mole42; 07-04-2008 at 02:27 PM.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    The two forms are equivalent. Just pick the form that's the most readable and let the compiler take care of optimizations.

    >> will the produced code just check v1 and v2, and ignore va,vb,vc and vd?
    Yes - the compiler should "shortcut" expression evaluation where it can.

    gg

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Depending on what f() does, it may or may not be the same.

    In the first case, f() can potentially be called twice. In the latter edition, it will only ever get called a max of once.
    Mainframe assembler programmer by trade. C coder when I can.

  4. #4
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> f() can potentially be called twice
    Good catch. Making the second "if" an "else if" makes my original statement correct.

    gg

  5. #5
    Registered User
    Join Date
    Jul 2008
    Posts
    26
    Corrected, that was my intention.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with making a Math Expression DLL
    By MindWorX in forum C Programming
    Replies: 19
    Last Post: 07-19-2007, 11:37 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. recursion error
    By cchallenged in forum C Programming
    Replies: 2
    Last Post: 12-18-2006, 09:15 AM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. Expression Evaluator Contest
    By Stack Overflow in forum Contests Board
    Replies: 20
    Last Post: 03-29-2005, 10:34 AM