Thread: Optimising an if statement

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    1

    Optimising an if statement

    Hello,
    Does anyone know which one of these two if statements that is fastest to execute?

    Code:
    #define ALPHA 0x01
    #define BETA 0x04
    #define GAMMA 0x08
    #define DELTA 0x10
    
    ...
    
    if (flag == ALPHA || flag == GAMMA)
    	printf("ok!");
    else
    	printf("error");
    
    if (flag & (ALPHA | GAMMA))
    	printf("ok!");
    else
    	printf("error");
    I know the first one is safer, but I think the later is faster. But I don't really know.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The first one and the second one are not comparible. The first one is wrong if you have more than one flag set on flag. The first one is only true if, and only if, flag is set to one flag. The second works for multiple flag sets, which is more than likely what you want.

    Example: The first one fails if you have both ALPHA and BETA set. The second will give you a true result if ALPHA and BETA are set, even though you're testing for ALPHA and GAMA.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Usefulness of the "else if" statement
    By gn17 in forum C Programming
    Replies: 7
    Last Post: 08-12-2007, 05:19 AM
  2. If Else statement problem
    By doofusboy in forum C Programming
    Replies: 2
    Last Post: 11-09-2005, 07:18 AM
  3. if/break statement
    By Apropos in forum C++ Programming
    Replies: 7
    Last Post: 02-22-2005, 02:33 PM
  4. string & if statement
    By Curacao in forum C++ Programming
    Replies: 4
    Last Post: 05-02-2003, 09:56 PM
  5. Uh-oh! I am having a major switch problem!
    By goodn in forum C Programming
    Replies: 4
    Last Post: 11-01-2001, 04:49 PM