Thread: More efficient way to structure this function?

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    30

    More efficient way to structure this function?

    I have the very basic function below:

    Code:
    int isEven(int x){
        return ((x%2) == 0) ? 1 : 0;
    }
    I was recommended to use something related to booleans to further improve this function, should I really look into that? It seems as if using booleans would give no advantage at all with this (besides quicker checking without having to compare the results with ==).

    Is there any way this code could be "cleaner"?

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    88
    Quote Originally Posted by Justin H View Post
    I have the very basic function below:

    Code:
    int isEven(int x){
        return ((x%2) == 0) ? 1 : 0;
    }
    I was recommended to use something related to booleans to further improve this function, should I really look into that? It seems as if using booleans would give no advantage at all with this (besides quicker checking without having to compare the results with ==).

    Is there any way this code could be "cleaner"?
    Code:
    int 
    isEven(int x)
    {
        return (1 & (x^1));
    }
    OR
    Code:
    int 
    isEven(int x)
    {
        return (!(x&1));
    }
    Last edited by sparkomemphis; 10-19-2012 at 05:34 PM.

  3. #3
    Registered User
    Join Date
    Jul 2012
    Posts
    8
    Yes, there is More efficient way to structure this function?-verde-gif:


    Code:
    int isEven(int x){
        return !(x%2);
    }


    I hope that I have helped More efficient way to structure this function?-smiled-gif.

  4. #4
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    It would be cleaner without the Ternary operator.

    I suggest looking up Boolean not operator.

    Edit: I am too slow today.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  5. #5
    Registered User
    Join Date
    Oct 2012
    Posts
    30
    Quote Originally Posted by rjjj View Post
    Yes, there is More efficient way to structure this function?-verde-gif:


    Code:
    int isEven(int x){
        return !(x%2);
    }


    I hope that I have helped More efficient way to structure this function?-smiled-gif.
    Code:
    printf("3 %c", (isEven(4)) ? 'Y' : 'N');
    I'm using that to test the function:

    Code:
    int isEven(int x){
        return  !(x%2);
    }
    Why does it say 3 (prints out the char Y) is even?

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Um, reality check:

    printf("3 %c", (isEven(4)) ? 'Y' : 'N');

    The argument is 4, so the function is actually working.

  7. #7
    Registered User
    Join Date
    Oct 2012
    Posts
    30
    Quote Originally Posted by whiteflags View Post
    Um, reality check:

    printf("3 %c", (isEven(4)) ? 'Y' : 'N');

    The argument is 4, so the function is actually working.
    Woops...

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Justin H
    I was recommended to use something related to booleans to further improve this function, should I really look into that? It seems as if using booleans would give no advantage at all with this (besides quicker checking without having to compare the results with ==).
    In C, zero values are false, non-zero values are true. The result of the operator == is either 0 or 1. Trying to do micro optimisations at this level tends to be silly with today's optimising compilers. I would suggest for clarity:
    Code:
    int isEven(int x) {
        return x % 2 == 0;
    }
    Using !(x % 2) works here too, but then conceptually the result of x % 2 is an integral, not boolean, value (even though it is of type int either way). Alternatively:
    Code:
    int isEven(int x) {
        return x & 1 == 0;
    }
    but an optimising compiler is likely to optimise the modulo version if it is slower, and so it is a question of whether you think the modulo version is more readable or the bitwise and version is more readable (to experienced programmers I daresay both are fine).

    If this is somehow a real performance bottleneck (I have a feeling it isn't), then you should check to see if you can get the compiler to inline this function, or else turn it into a macro (but beware the pitfalls of macros), e.g.,
    Code:
    #define IS_EVEN(x) ((x) % 2 == 0)
    Oh, and of course remember to test that the change really is an improvement.
    Last edited by laserlight; 10-19-2012 at 11:31 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Ticked and off
    Join Date
    Oct 2011
    Location
    La-la land
    Posts
    1,728
    Quote Originally Posted by laserlight View Post
    If this is somehow a real performance bottleneck (I have a feeling it isn't), then you should check to see if you can get the compiler to inline this function
    If I may interject, that would be just
    Code:
    static inline int isEven(const int x)
    {
        return ((x % 2) == 0);
    }
    The static keyword makes the function only visible only in the current compilation unit (the current file, or current files if this is in a header file included by a source file). The actual point, however, is that most older C, and all C99 and C++ compilers, treat static inline functions as efficiently as macros.

    (In case you wonder, the parentheses are just my style.)

    C99 compilers (if using gcc, use the -std=c99 option) provide a true boolean type, _Bool. The equality operator == does yield an int (1 if equal, 0 otherwise), but you can just cast it to the boolean type. In C99, you can write the inline function thus:
    Code:
    static inline _Bool isEven(const int x)
    {
        return (_Bool)((x % 2) == 0);
    }
    I would personally omit the cast, because the compiler will do it for you, and it does not make the code any easier to read.

    Should you do the above?

    In my opinion, static inline is portable and very useful, and does work -- in the cases I tested, they were just as fast as macros. Writing a function is certainly easier than writing a macro, if you need anything more complex than one simple expression -- and because of that, my more complicated inline functions were sometimes faster than the macros I came up with.

    However, with more complex functions, you may be fighting yourself: because of CPU architecture details, the overall code might be faster when the code is not inlined; this is typical when the inlined code is long, but rarely executed. So, leave the optimization for the last step. You can mark the functions just static, and when the program is near ready, consider if the most often used helpers should be static inline or not.

    (For simple accessor functions (set/get value in a multidimensional array), I often have a macro without any error checking, and an inline function with bounds checking. I then use the macro everywhere I know I am within the bounds, and the inline functions where I think I might go over the bounds.)

    I write C99 almost exclusively, but I practically never use the _Bool type. I don't know exactly why. I suspect it is because usually my functions return zero for success, and an error code otherwise (usually reusing the errno constants). I guess I rarely use pure boolean return values for my functions.

    Of course, if you don't want to be limited to C99 and C11, you should not rely on _Bool anyway.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. more efficient prime function??
    By codingGuy in forum C Programming
    Replies: 10
    Last Post: 10-12-2011, 05:09 PM
  2. Replies: 4
    Last Post: 04-25-2010, 10:57 AM
  3. Deciding on efficient data structure??
    By ts4 in forum C Programming
    Replies: 1
    Last Post: 06-21-2007, 02:24 PM
  4. Structure to/from function
    By vb.bajpai in forum C Programming
    Replies: 2
    Last Post: 06-17-2007, 11:55 AM
  5. Structure and Function
    By DocDroopy in forum C Programming
    Replies: 9
    Last Post: 08-03-2002, 11:14 AM