Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 527763
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T08:55:02+00:00 2026-05-13T08:55:02+00:00

I’m going through quiz answers from my professor and a question was: the correct

  • 0

I’m going through quiz answers from my professor and a question was:

the correct implementation of a function like macro for absolute value is:

#define abs(x) ((x)<0 ? (-x) : (x))
#define abs(x) ((x)<0 ? -(x) : (x))

Why is the second one correct vs the first one?

And why do you have to use all the (). Like what are the rules involved? Every variable needs a ()? Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T08:55:02+00:00Added an answer on May 13, 2026 at 8:55 am

    There are various related problems that the extra parentheses solve. I’ll go through them one by one:

    Try: int y = abs( a ) + 2

    Let’s assume you use:

    #define abs(x)  (x<0)?-x:x
    ...
        int y = abs( a ) + 2
    

    This expands to int y = (a<0)?-a:a+2. The +2 binds only to the false result. 2 is only added when a is positive, not when it is negative. So we need parenthesis around the whole thing:

    #define abs(x)  ( (x<0) ? -x : x )
    

    Try: int y = abs(a+b);

    But then we might have int y = abs(a+b) which gets expanded to int y = ( (a+b<0) ? -a+b : a+b). If a + b is negative then b is not negated when they add for the result. So we need to put the x of -x in parentheses.

    #define abs(x)  ( (x<0) ? -(x) : x )
    

    Try: int y = abs(a=b);

    This ought to be legal (though bad), but it expands to int y = ( (a=b<0)?-(a=b):a=b ); which tries to assign the final b to the ternary. This should not compile. (Note that it does in C++. I had to compile it with gcc instead of g++ to see it fail to compile with the “invalid lvalue in assignment” error.)

    #define abs(x)  ( (x<0) ? -(x) : (x) )
    

    Try: int y = abs((a<b)?a:b);

    This expands to int y = ( ((a<b)?a:b<0) ? -((a<b)?a:b) : (a<b)?a:b ), which groups the <0 with the b, not the entire ternary as intended.

    #define abs(x)  ( ( (x) < 0) ? -(x) : (x) )
    

    In the end, each instance of x is prone to some grouping problem that parentheses are needed to solve.

    Common problem: operator precedence

    The common thread in all of these is operator precedence: if you put an operator in your abs(...) invocation that has lower precedence then something around where x is used in the macro, then it will bind incorrectly. For instance, abs(a=b) will expand to a=b<0 which is the same as a=(b<0)… that isn’t what the caller meant.

    The “Right Way” to Implement abs

    Of course, this is the wrong way to implement abs anyways… if you don’t want to use the built in functions (and you should, because they will be optimized for whatever hardware you port to), then it should be an inline template (if using C++) for the same reasons mentioned when Meyers, Sutter, et al discuss re-implementing the min and max functions. (Other answers have also mentioned it: what happens with abs(x++)?)

    Off the top of my head, a reasonable implementation might be:

    template<typename T> inline const T abs(T const & x)
    {
        return ( x<0 ) ? -x : x;
    }
    

    Here it is okay to leave off the parentheses since we know that x is a single value, not some arbitrary expansion from a macro.

    Better yet, as Chris Lutz pointed out in the comments below, you can use template specialization to call the optimized versions (abs, fabs, labs) and get all the benefits of type safety, support for non-builtin types, and performance.

    Test Code

    #if 0
    gcc $0 -g -ansi -std=c99 -o exe && ./exe
    exit
    #endif
    
    
    
    
    #include <stdio.h>
    
    #define abs1(x)  (x<0)?-x:x
    #define abs2(x)  ((x<0)?-x:x)
    #define abs3(x)  ((x<0)?-(x):x)
    #define abs4(x)  ((x<0)?-(x):(x))
    #define abs5(x)  (((x)<0)?-(x):(x))
    
    
    #define test(x)     printf("//%30s=%d\n", #x, x);
    #define testt(t,x)  printf("//%15s%15s=%d\n", t, #x, x);
    
    int main()
    {
        test(abs1( 1)+2)
        test(abs1(-1)+2)
        //                    abs1( 1)+2=3
        //                    abs1(-1)+2=1
    
        test(abs2( 1+2))
        test(abs2(-1-2))
        //                    abs2( 1+2)=3
        //                    abs2(-1-2)=-1
    
        int a,b;
        //b =  1; testt("b= 1; ", abs3(a=b))
        //b = -1; testt("b=-1; ", abs3(a=b))
        // When compiled with -ansi -std=c99 options, this gives the errors:
        //./so1a.c: In function 'main':
        //./so1a.c:34: error: invalid lvalue in assignment
        //./so1a.c:35: error: invalid lvalue in assignment
    
        // Abs of the smaller of a and b. Should be one or two.
        a=1; b=2; testt("a=1; b=2; ", abs4((a<b)?a:b))
        a=2; b=1; testt("a=2; b=1; ", abs4((a<b)?a:b))
        //               abs4((a<b)?a:b)=-1
        //               abs4((a<b)?a:b)=1
    
    
        test(abs5( 1)+2)
        test(abs5(-1)+2)
        test(abs5( 1+2))
        test(abs5(-1-2))
        b =  1; testt("b= 1; ", abs5(a=b))
        b = -1; testt("b=-1; ", abs5(a=b))
        a=1; b=2; testt("a=1; b=2; ", abs5((a<b)?a:b))
        a=2; b=1; testt("a=2; b=1; ", abs5((a<b)?a:b))
    }
    

    Output

                        abs1( 1)+2=3
                        abs1(-1)+2=1
                        abs2( 1+2)=3
                        abs2(-1-2)=-1
         a=1; b=2; abs4((a<b)?a:b)=-1
         a=2; b=1; abs4((a<b)?a:b)=1
                        abs5( 1)+2=3
                        abs5(-1)+2=3
                        abs5( 1+2)=3
                        abs5(-1-2)=3
             b= 1;       abs5(a=b)=1
             b=-1;       abs5(a=b)=1
         a=1; b=2; abs5((a<b)?a:b)=1
         a=2; b=1; abs5((a<b)?a:b)=1
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
For some reason, after submitting a string like this Jack’s Spindle from a text
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
This could be a duplicate question, but I have no idea what search terms
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.