Thread: Ternary operator

  1. #1
    Registered User
    Join Date
    Oct 2018
    Posts
    1

    Ternary operator

    Hello everyone

    A newbie in C i am and this is my first post / question

    What is the difference between

    #define getmax(x,y) ((x)>(b)?(x)y))

    and

    #define getmax(x,y) (x > y) ? x : y

    Why the need for parentheses in the first version ?

    Thanks in advance

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Compile and run this program:
    Code:
    #include <stdio.h>
    
    #define getmax_v1(x, y) ((x) > (y) ? (x) : (y)) 
    
    #define getmax_v2(x, y) (x > y) ? x : y
    
    int main(void)
    {
        int a = 10;
        int b = 20;
    
        printf("v1: %d\n", getmax_v1(a, b + 1) * 2);
        printf("v2: %d\n", getmax_v2(a, b + 1) * 2);
    
        return 0;
    }
    In general, to avoid these kinds of problems, unless the expression is already a primary expression (e.g., a constant), we surround the entire expression in a pair of parentheses, and surround each of the macro identifiers in the expression with parentheses as they could be complex expressions, so this eliminates the chance that precedence rules might cause an unexpected result.
    Last edited by laserlight; 10-22-2018 at 03:31 AM.
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Ternary operator
    By kkk in forum C Programming
    Replies: 12
    Last Post: 07-03-2011, 11:35 PM
  2. Ternary Operator to choose which operator to use
    By cncool in forum C Programming
    Replies: 7
    Last Post: 06-27-2011, 01:35 PM
  3. bug in ternary operator ?:
    By wiglaf in forum C Programming
    Replies: 14
    Last Post: 03-31-2011, 10:26 PM
  4. Is the PHP ternary operator broken?
    By mike_g in forum Tech Board
    Replies: 13
    Last Post: 07-18-2009, 05:04 PM
  5. ternary operator
    By abhijith gopal in forum C Programming
    Replies: 37
    Last Post: 07-10-2006, 11:58 AM

Tags for this Thread