Thread: C macros

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    2

    C macros

    Hi,

    Im new to C programming and having trouble understanding the output of this program.
    Code:
    #define MAX(x,y) (x)>(y)?(x):(y)
    void main( )
    {
    int i=10;
    j=5;
    k=0;
    k=MAX(i++,++j);
    printf(%d %d %d %d,i,j,k);
    Will really appreciate if someone can explain the logic of the output
    Last edited by Salem; 01-26-2011 at 08:20 AM. Reason: Added [code][/code] tags - learn to use them yourself

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I believe it should be undefined behavior. You have multiple increments and decrements in a single execution point. That means the output is undefined:
    Code:
    k = (i++) > (j++) ? (j++) : (i++);
    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jan 2011
    Posts
    2
    the output im getting is 12 6 11.dont know how?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    ?: is a sequence point, so you should be OK on that front.
    Question 3.8

    Perhaps try to write the statement as a rather more verbose if / else statement instead?
    It will help you to see when things get incremented, compared, assigned.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    a > b ? true_exp : false_exp;

    Take note that only either true_exp or false_exp is evaluated.

    (i++) > (j++) ? (i++) : (j++)

    If i++ is greater than j++, only i++(true_exp) is evaluated. causing i value incremented twice.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Order of execution of preprocessor macros
    By DL1 in forum C Programming
    Replies: 2
    Last Post: 04-02-2009, 06:52 PM
  2. parameterized macros vs. functions
    By Tbrez in forum C Programming
    Replies: 3
    Last Post: 04-02-2009, 12:33 PM
  3. function definition with macros
    By toshog in forum C++ Programming
    Replies: 2
    Last Post: 03-08-2009, 09:22 PM
  4. Pre-processor macros causing segfaults
    By nempo in forum C++ Programming
    Replies: 6
    Last Post: 02-10-2009, 02:35 AM
  5. Macros inside of macros
    By Chewie8 in forum C Programming
    Replies: 2
    Last Post: 02-24-2008, 03:51 AM